1

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?

3
  • Can you please define not working anymore? What's the behavior now? Commented May 9, 2018 at 2:52
  • I am unable to call a function in ngFor Commented May 9, 2018 at 2:54
  • stackblitz.com/edit/angular-xwgjpz I've copied exactly your code and stackblitz runs it. Commented May 9, 2018 at 3:21

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your quick replay but getting TypeError: Cannot read property 'map' of undefined
import { map } from 'rxjs';
imported using import{map} from 'rxjs/operators/map'; but showing same error
probably just missing 'this'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.