Reputation: 574
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?
Upvotes: 1
Views: 774
Reputation: 52867
I would recommend transforming your data structure into something more useful - maybe behind a service:
groups: any =
this.Categories.map(t=> {
return {
id: t.id,
name: t.name,
articles: this.Articles.filter(x=>x.categoryId == t.id)
}
});
Then in your template:
<ul>
<li *ngFor="let group of groups">
{{group.name}}
<ul>
<li *ngFor="let article of group.articles">
{{article.name }}
</li>
</ul>
</li>
</ul>
Upvotes: 1