ng用于重复组件
ngFor repeating Components
我有两个组件,一个是 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;
}
}
另一个是新闻源:
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);
}
}
有没有办法让我使用 post 中的模板重复每个 post,而不是仅仅使用对象语法或在新闻源中格式化 post。也许我是 ang2 的新手,所以我以错误的方式处理这个问题。感谢任何帮助。
非常感谢。
事实上,Angular2 会为您实例化组件。只需在 ngFor 循环中添加选择器标签:
<ul>
<li *ngFor="#postData of posts">
<post [title]="postData.title"
[postTest]="postData.postText"></post>
</li>
</ul>
您的 post 数据必须这样定义:
posts : any[];
constructor() {
this.posts =[];
this.posts.push({title:"Post1",postText:"Wow greate post"});
this.posts.push({title:"Such Post", postText:"WoW"});
}
为此,您需要稍微重构您的组件以添加输入:
@Component({
selector: 'post',
template: `
<h1>{{title}}</h1>
<p>{{postText}}</p>
`
})
export class Post {
@Input() // <-----
title : string;
@Input() // <-----
postText : string;
}
我有两个组件,一个是 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;
}
}
另一个是新闻源:
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);
}
}
有没有办法让我使用 post 中的模板重复每个 post,而不是仅仅使用对象语法或在新闻源中格式化 post。也许我是 ang2 的新手,所以我以错误的方式处理这个问题。感谢任何帮助。
非常感谢。
事实上,Angular2 会为您实例化组件。只需在 ngFor 循环中添加选择器标签:
<ul>
<li *ngFor="#postData of posts">
<post [title]="postData.title"
[postTest]="postData.postText"></post>
</li>
</ul>
您的 post 数据必须这样定义:
posts : any[];
constructor() {
this.posts =[];
this.posts.push({title:"Post1",postText:"Wow greate post"});
this.posts.push({title:"Such Post", postText:"WoW"});
}
为此,您需要稍微重构您的组件以添加输入:
@Component({
selector: 'post',
template: `
<h1>{{title}}</h1>
<p>{{postText}}</p>
`
})
export class Post {
@Input() // <-----
title : string;
@Input() // <-----
postText : string;
}