angular – ng用于重复组件

前端之家收集整理的这篇文章主要介绍了angular – ng用于重复组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个组件,一个是Post:
  1. import {Component} from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'post',template: `
  5. <h1>{{title}}</h1>
  6. <p>{{postText}}</p>
  7. `
  8. })
  9. export class Post {
  10. title : string;
  11. postText : string;
  12. constructor(title:string,postText:string) {
  13. this.title = title;
  14. this.postText = postText;
  15. }
  16. }

另一个是新闻源:

  1. import {Component} from '@angular/core';
  2. import {Post} from "./app.post.component";
  3.  
  4. @Component({
  5. selector: 'news-Feed',template: `
  6. <h1>News Feed</h1>
  7. <ul *ngFor='#post of posts'>
  8. <li *ngFor='#post of posts'>
  9. {{post | json}}
  10. </li>
  11. </ul>
  12. `
  13. })
  14. export class NewsFeed {
  15. posts : Post[];
  16. constructor() {
  17. let p1 = new Post("Post1","Wow greate post");
  18. let p2 = new Post("Such Post","WoW");
  19. this.posts =[];
  20. this.posts.push(p1);
  21. this.posts.push(p2);
  22. }
  23. }

有没有办法让我在帖子中使用模板重复每个帖子,而不是仅使用对象语法或格式化新闻源内的帖子.也许我正在以错误的方式接近这个,因为我是ang2的新手.任何帮助表示赞赏.

非常感谢你.

事实上,Angular2将为您实例化组件.只需在ngFor循环中添加选择器标记
  1. <ul>
  2. <li *ngFor="#postData of posts">
  3. <post [title]="postData.title"
  4. [postTest]="postData.postText"></post>
  5. </li>
  6. </ul>

您的帖子数据必须以这种方式定义:

  1. posts : any[];
  2. constructor() {
  3. this.posts =[];
  4. this.posts.push({title:"Post1",postText:"Wow greate post"});
  5. this.posts.push({title:"Such Post",postText:"WoW"});
  6. }

为此,您需要重构一下您的组件以添加输入:

  1. @Component({
  2. selector: 'post',template: `
  3. <h1>{{title}}</h1>
  4. <p>{{postText}}</p>
  5. `
  6. })
  7. export class Post {
  8. @Input() // <-----
  9. title : string;
  10. @Input() // <-----
  11. postText : string;
  12. }

猜你在找的Angularjs相关文章