【问题标题】:ngFor repeating ComponentsngFor 重复组件
【发布时间】:2016-09-27 23:01:15
【问题描述】:

我有两个组件,一个是 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 的新手,所以我可能以错误的方式处理这个问题。任何帮助表示赞赏。

非常感谢。

【问题讨论】:

  • 清楚地发布问题你想做什么?

标签: angular components


【解决方案1】:

其实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;
}

【讨论】:

  • 不客气!事实上你可以;-) 它会是这样的:&lt;post [post]="postData" ... 在你的组件中:@Input() post:any;
  • 嘿@ThierryTemplier,你知道是否可以在ngFor中包含不同的组件。例如,在这个问题中,假设我有 post-textpost-article 组件,我需要在 for 循环中执行类似 &lt;post-{{postData.type}} [post]="postData"... 的操作。谢谢
  • @NoopurDabhi 我认为你应该使用 *ngIf 或 *ngSwitch 像 &lt;post-text *ngIf="postData.type === 'text'"... 等等。但也许在 Angular 4/5 中有更好的方法。自从提出这个问题以来,许多事情都发生了变化..(如果你能找到它,请告诉我:))
  • 我找到了解决方案...我使用了这个pluker ...而不是调用按钮onclick函数,我将组件的选择器标签放在循环中,并且在组件中,我使用了与pluker中提到了
  • 漂亮的答案!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 2017-03-11
相关资源
最近更新 更多