Angular2 UL/LI JSON-tree recursive in ngFor

user3601578 picture user3601578 · Mar 1, 2016 · Viewed 15.4k times · Source

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:[]}
                             ]
                    }
                 ]
        }
    ]

to this unordered list

<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>

using Angular2 and ngFor. Anyone got an idea?

Answer

James Bradford picture James Bradford · May 7, 2017

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 #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>

Here's a gist.