Display nested List using ngFor -Angular2

时间:2018-05-09 02:50:26

标签: angular typescript

I've created a list with different categories and created another list with articles, in articles list i am maintaining categoryId which is id in categories list.

Now I wanted to display categories and need to display articles based on the category.

Here my code is:

List of categories and articles

Articles:Article[] =[{id:1,name:'Article1',categoryId:1,publichedOn:new Date,description:'Article1 '},{id:2,name:'Article2',categoryId:1,publichedOn:new Date,description:'Article2 '},{id:3,name:'Article3',categoryId:2,publichedOn:new Date,description:'Article3 '},{id:4,name:'Article4',categoryId:2,publichedOn:new Date,description:'Article4 '},{id:5,name:'Article5',categoryId:3,publichedOn:new Date,description:'Article5 '},{id:1,name:'Article6',categoryId:3,publichedOn:new Date,description:'Article6 '}]


Categories:Category[] =[{id:1,name:'Category1'},{id:2,name:'Category2'},{id:3,name:'Category3'},]

Displaying list of categories and articles

 <ul>
    <li *ngFor="let category of categories">
    {{category.name}}
    <ul>
        <li *ngFor="let article of getArticlesForCategory(category.id)">
        {{article.name }}
        </li>
    </ul>
    </li>
</ul>

getArticlesForCategory function will return the articlesList based on the category id.

Tried to display articles based on the returned list but i am unable to call function from ngFor

am i missed any thing? or Is There any other way to do the same?

1 个答案:

答案 0 :(得分:1)

我建议将您的数据结构转换为更有用的东西 - 可能在服务后面:

groups: any = 
     this.Categories.map(t=> { 
        return { 
            id: t.id, 
            name: t.name, 
            articles: this.Articles.filter(x=>x.categoryId == t.id) 
        } 
     });

然后在你的模板中:

<ul>
    <li *ngFor="let group of groups">
    {{group.name}}
    <ul>
        <li *ngFor="let article of group.articles">
        {{article.name }}
        </li>
    </ul>
    </li>
</ul>