通过子项无限嵌套ngFor [英] Unlimited nested ngFor through child items
本文介绍了通过子项无限嵌套ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Angular2中发现了几个有关嵌套ngFor循环的问题,但不是我要寻找的问题.我想在列表中显示类别.我的JSON看起来像这样:
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#类如下:
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; }
}
现在的诀窍是在ngFor循环中获得此效果,而对子项的深度没有任何限制.
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;
}
这篇关于通过子项无限嵌套ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文