2016-05-30 14 views
6

私は1つのポストである二つの成分を持っている: ngFor繰り返しコンポーネント

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); 
    } 
} 

は私がポストでテンプレートを使用して、各ポストを繰り返すのではなくするための方法があります:

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

他のニュースフィードですオブジェクト構文を使用するか、ニュースフィード内の投稿を書式設定するだけです。おそらく、私はang2を初めて使ったので、間違った方法でこれに近づいています。どんな助けもありがとうございます。

ありがとうございました。

+0

投稿の質問明確に何をしたいのですか? –

答えて

9

実際、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; 
} 
+0

あなたは大歓迎です!実際、あなたはそうすることができます;-)それは、次のようなものでしょう: '

+1

Hey @ThierryTemplier、 ngForに異なるコンポーネントを含めることが可能かどうかを知る。例えば、この質問のように、私は 'post-text'と' post-article'のcompoenetsを持っていて、 '

+0

@NoopurDabhi私はあなたが '

関連する問題