ngFor 中的 Angular2 UL/LI JSON 树递归 [英] Angular2 UL/LI JSON-tree recursive in ngFor
本文介绍了ngFor 中的 Angular2 UL/LI JSON 树递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Angular2 中将 JSON 树转换为无序列表.我知道来自 Angular1 的递归指令解决方案,我很确定 Angular2 中的解决方案也将是递归的.
I'd like to convert JSON-trees into unordered lists in Angular2. I know the recursive directive solution from Angular1 and I am pretty sure the solution in Angular2 will be recursive too.
[
{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.有人有想法吗?
using Angular2 and ngFor. Anyone got an idea?
推荐答案
借鉴 Torgeir Helgevold 的帖子,我想出了这个Plunkr.代码如下:
Borrowing from Torgeir Helgevold's post, I came up with this Plunkr. Here's the code:
树视图组件:
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:[]}
]
}
]
}
];
}
这篇关于ngFor 中的 Angular2 UL/LI JSON 树递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文