Angular2 UL / LI JSON-tree在ngFor中递归

时间:2016-03-01 20:49:27

标签: json tree html-lists angular

我想将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 个答案:

答案 0 :(得分:30)

您不需要制作新的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>

这里是gist

答案 1 :(得分:28)

借鉴Torgeir Helgevold's post,我提出了this 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:[]}
                             ]
                    }
                 ]
        }
    ];
}