I found a couple of questions about nested ngFor loops in Angular2 but not what i'm looking for. I want to show categories in a list. My JSON looks like this:
{
Categories: [{
"Title": "Categorie A",
"Children": [
{
"Title": "Sub Categorie A",
"Children": []
}
]
},{
"Title": "Categorie B",
"Children": [
{
"Title": "Sub Categorie B",
"Children": [{
"Title": "Sub Sub Categorie A",
"Children": []
}]
}
]
}]
}
C# class looks like this:
public class Child
{
public string Title { get; set; }
public List<object> Children { get; set; }
}
public class Category
{
public string Title { get; set; }
public List<Child> Children { get; set; }
}
Now the trick is to get this in a ngFor loop without any restrictions on the depth of children.
I think this would be pretty straightforward with a component that renders itself as child elements:
export interface Category {
Title: string;
Children: Category[];
}
@Component({
selector: 'my-category',
template: `
<h2>{{ category.Title }}</h2>
<ul *ngIf="category.Children.length > 0">
<li *ngFor="let child of category.Children">
<my-category [category]="child"></my-category>
</li>
</ul>
`
})
export class MyCategoryComponent {
@Input() category: Category;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With