我有两个组件,一个是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);
- }
- }
有没有办法让我在帖子中使用模板重复每个帖子,而不是仅使用对象语法或格式化新闻源内的帖子.也许我正在以错误的方式接近这个,因为我是ang2的新手.任何帮助表示赞赏.
非常感谢你.
事实上,Angular2将为您实例化组件.只需在ngFor循环中添加选择器标记:
- <ul>
- <li *ngFor="#postData of posts">
- <post [title]="postData.title"
- [postTest]="postData.postText"></post>
- </li>
- </ul>
您的帖子数据必须以这种方式定义:
- 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;
- }