Skip to content Skip to sidebar Skip to footer

Angular2 Ul/li Json-tree Recursive In Ngfor

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 recursi

Solution 1:

You don't need to make a new tree-view component to do this, you can simply use this pattern in any of your templates:

If your data array was public property list of your component:

<h1>Angular 2 Recursive List</h1><ul><ng-template #recursiveListlet-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>

Here's a gist.

Solution 2:

Borrowing from Torgeir Helgevold's post, I came up with this Plunkr. Here's the code:

TreeView Component:

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 classTreeView {
  @Input() treeData: [];
}

App Component:

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 classAppComponent { 
  myTree =     [
        {name:"parent1", subnodes:[]},
        {name:"parent2", 
            subnodes:[
                    {name:"parent2_child1", subnodes:[]}
                 ],
        {name:"parent3", 
            subnodes:[
                    {name:"parent3_child1", 
                        subnodes:[
                                {name:"parent3_child1_child1", subnodes:[]}
                             ]
                    }
                 ]
        }
    ];
}

Post a Comment for "Angular2 Ul/li Json-tree Recursive In Ngfor"