[英]Angular6 ngFor directive n-dimentional array
I have an array with objects which can contain childs. 我有一个包含可以包含子对象的对象的数组。 And the childs can also contain childs. 并且孩子也可以包含孩子。 And so on. 等等。
[
{
name: '1',
children: [
{
name: '1.1',
},
{
name: '1.2',
children: [
{
name: '1.2.1'
}
]
}
]
},
{
name: '2'
}
]
I wrote this and it works for 2 levels but I want it to work with n levels: 我写了这个,它适用于2个级别,但我希望它可以与n个级别一起使用:
<li *ngFor="let item of items">
{{item.name}}
<ul>
<li *ngFor="let child of item.children">
{{child.name}}
</li>
</ul>
</li>
I could generate it all with typescript, but is there a way to do this with template directives? 我可以使用typescript生成所有内容,但是有没有办法使用模板指令来生成?
Yes, it's possible using templates ( ng-template
/ ngTemplateOutlet
): 是的,可以使用模板( ng-template
/ ngTemplateOutlet
):
https://stackblitz.com/edit/angular-bu9poh?file=src%2Fapp%2Fapp.component.html https://stackblitz.com/edit/angular-bu9poh?file=src%2Fapp%2Fapp.component.html
<div>Hello world!</div>
<ng-container *ngTemplateOutlet="itemsTemplate;context:{items:items}"></ng-container>
<ng-template #itemsTemplate let-items="items">
<div *ngFor="let item of items">
Name: {{item.name}}<br/>
Children:
<div style="margin-left:20px">
<ng-container *ngTemplateOutlet="itemsTemplate;context:{items:item.children}"></ng-container>
</div>
</div>
</ng-template>
You can use ul/li instead of divs. 您可以使用ul / li代替divs。
You can use recursive html as this link 您可以使用递归html作为此链接
<ul>
<ng-template #recursiveList let-list>
<li *ngFor="let item of items">
{{item.name}}
<ul *ngIf="item.children.length > 0">
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }"></ng-container>
</ul>
</li>
</ng-template>
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
</ul>
hope this helps. 希望这可以帮助。
A really simple way to do it which is also much more suitable for complex components is to use recursive components. 一个非常简单的方法(也更适合于复杂组件)是使用递归组件。
The end result: 最终结果:
<app-recursive *ngFor="let item of items" [item]="item"></app-recursive>
The recursive component: 递归组件:
<div>Name: {{item.name}}</div>
<app-recursive *ngFor="let child of item.children" [item]="child"></app-recursive>
Its typescript: 其打字稿:
@Input('item') public item: any;
Demo: https://stackblitz.com/edit/angular-7azst4?file=src%2Fapp%2Fapp.component.html 演示: https : //stackblitz.com/edit/angular-7azst4?file=src%2Fapp%2Fapp.component.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.