Ng For repetition of components

I have two 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; } } 

the other is a news feed:

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

Is there a way to repeat each message using the template in the column, and not just use the object syntax or format the message inside the feed. Perhaps I am approaching this incorrectly as I am new to ang2. Any help is appreciated.

Many thanks.

+6
source share
1 answer

In fact, Angular2 will instantiate the component for you. Just add a selector tag to the ngFor loop:

 <ul> <li *ngFor="#postData of posts"> <post [title]="postData.title" [postTest]="postData.postText"></post> </li> </ul> 

Your data should be defined as follows:

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

To do this, you need to reorganize the bit of your component to add inputs:

 @Component({ selector: 'post', template: ` <h1>{{title}}</h1> <p>{{postText}}</p> ` }) export class Post { @Input() // <----- title : string; @Input() // <----- postText : string; } 
+9
source

All Articles