I have a json
file with categories and a lot of sub categories. Inside sub categories there are more sub categories and so on. How can I easy write a loop in my template to show categories? I tried *ngFor
loop and inside another *ngFor
. All works fine. But in this way I have to do it again and again. Also I can't know before how many sub categories exist. Is there a easy way to go deeper if a subcategorie exist?
{
"data": [
{
"id": 1,
"name": "main category",
"subcategory": [
{
"id": 2,
"name": "sub category",
"subcategorie": [
{
"id": 3,
"name": "sub sub category",
"subcategorie": [
{
"id": 4,
"name": "sub sub sub category",
"subcategorie": []
}
]
},
{
"id": 5,
"name": "sub sub category",
"subcategorie": []
}
]
}
]
}
]
}
Final solution (if anybody has same need):
<div *ngFor="let category of categories">
<h1>{{ category.name }}</h1>
<app-show-categories [categories]="category.subcategory"></app-show-categories>
</div>
Also use nested inside nested:
<div *ngFor="let subcategory of categories">
{{ subcategory.name }}
<app-show-categories [categories]="item.subcategory"></app-show-categories>
</div>
Nested ShowCategoriesComponent:
export class ShowCategoriesComponent {
@Input() categories: Categories[];
constructor() { }
ngOnInit(): void {
console.warn(this.categories);
}
}