Angular2 UL / LI JSON-дерево рекурсивное в ngFor
Я хотел бы преобразовать JSON-деревья в неупорядоченные списки в Angular2. Я знаю рекурсивное директивное решение из Angular1, и я уверен, что решение в Angular2 тоже будет рекурсивным.
[
{name:"parent1", subnodes:[]},
{name:"parent2",
subnodes:[
{name:"parent2_child1", subnodes:[]}
],
{name:"parent3",
subnodes:[
{name:"parent3_child1",
subnodes:[
{name:"parent3_child1_child1", subnodes:[]}
]
}
]
}
]
к этому неупорядоченному списку
<ul>
<li>parent1</li>
<li>parent2
<ul>
<li>parent2_child1</li>
</ul>
</li>
<li>parent3
<ul>
<li>parent3_child1
<ul>
<li>parent3_child1_child1</li>
</ul>
</li>
</ul>
</li>
</ul>
используя Angular2 и ngFor. У кого-нибудь есть идеи?
2 ответов
заимствование из пост Торгейра Хельгевольда, Я придумал это Plunkr. Вот код:
Компонент TreeView:
import {Component, Input} from 'angular2/core';
@Component ({
selector: 'tree-view',
directives: [TreeView],
template: `
<ul>
<li *ngFor="#node of treeData">
{{node.name}}
<tree-view [treeData]="node.subnodes"></tree-view>
</li>
</ul>
`
})
export class TreeView {
@Input() treeData: [];
}
Приложение Компонент:
import {Component} from 'angular2/core';
import {TreeView} from './tree-view.component';
@Component({
selector: 'my-app',
directives: [TreeView],
template: `
<h1>Tree as UL</h1>
<tree-view [treeData]="myTree"></tree-view>
`
})
export class AppComponent {
myTree = [
{name:"parent1", subnodes:[]},
{name:"parent2",
subnodes:[
{name:"parent2_child1", subnodes:[]}
],
{name:"parent3",
subnodes:[
{name:"parent3_child1",
subnodes:[
{name:"parent3_child1_child1", subnodes:[]}
]
}
]
}
];
}
вам не нужно делать новый tree-view
компонент для этого вы можете просто использовать этот шаблон в любом из ваших шаблонов:
Если Ваш массив данных был общественной собственностью list
компонента:
<h1>Angular 2 Recursive List</h1>
<ul>
<ng-template #recursiveList let-list>
<li *ngFor="let item of list">
{{item.name}}
<ul *ngIf="item.subnodes.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>
здесь суть.