通过子项无限制嵌套ngFor

时间:2017-04-15 21:08:13

标签: c# .net angular

我在Angular2中发现了几个关于嵌套ngFor循环的问题,但没有找到我正在寻找的东西。我想在列表中显示类别。我的JSON看起来像这样:

{
    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循环中获取它,而不会对子项的深度有任何限制。

1 个答案:

答案 0 :(得分:4)

我认为使用将自身呈现为子元素的组件非常简单:

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;
}