Sam*_*rts 12 components angular
我有两个组件,一个是Post:
import {Component} from '@angular/core';
@Component({
selector: 'post',
template: `
<h1>{{title}}</h1>
<p>{{postText}}</p>
`
})
export class Post {
title : string;
postText : string;
constructor(title:string, postText:string) {
this.title = title;
this.postText = postText;
}
}
Run Code Online (Sandbox Code Playgroud)
另一个是新闻源:
import {Component} from '@angular/core';
import {Post} from "./app.post.component";
@Component({
selector: 'news-feed',
template: `
<h1>News Feed</h1>
<ul *ngFor='#post of posts'>
<li *ngFor='#post of posts'>
{{post | json}}
</li>
</ul>
`
})
export class NewsFeed {
posts : Post[];
constructor() {
let p1 = new Post("Post1","Wow greate post");
let p2 = new Post("Such Post", "WoW");
this.posts =[];
this.posts.push(p1);
this.posts.push(p2);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让我在帖子中使用模板重复每个帖子,而不是仅仅使用对象语法或格式化新闻源内的帖子.也许我正在以错误的方式接近这个,因为我是ang2的新手.任何帮助表示赞赏.
非常感谢你.
Thi*_*ier 15
实际上,Angular2将为您实例化组件.只需在ngFor循环中添加选择器标记:
<ul>
<li *ngFor="#postData of posts">
<post [title]="postData.title"
[postTest]="postData.postText"></post>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
您的帖子数据必须以这种方式定义:
posts : any[];
constructor() {
this.posts =[];
this.posts.push({title:"Post1",postText:"Wow greate post"});
this.posts.push({title:"Such Post", postText:"WoW"});
}
Run Code Online (Sandbox Code Playgroud)
为此,您需要重构一下您的组件以添加输入:
@Component({
selector: 'post',
template: `
<h1>{{title}}</h1>
<p>{{postText}}</p>
`
})
export class Post {
@Input() // <-----
title : string;
@Input() // <-----
postText : string;
}
Run Code Online (Sandbox Code Playgroud)