[英]Angular2 UL/LI JSON-tree recursive in 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。 有人有個主意嗎?
您不需要創建新的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.children.length > 0"> <!-- item.subnodes.length -->
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }"></ng-container>
</ul>
</li>
</ng-template>
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
</ul>
這是一個要點 。
借用Torgeir Helgevold的帖子 ,我想出了這個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:[]}
]
}
]
}
];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.