Angular 2: Recursive template for child

Glenn Utter picture Glenn Utter · Jan 30, 2017 · Viewed 7.6k times · Source

The API I am working against gives me the following structure in response:

"data": [
{
  "id": 5,
  "name": "First name",
  "parent": 0
},
{
  "id": 1,
  "name": "Second name",
  "parent": 5
},
{
  "id": 6,
  "name": "Third name",
  "parent": 1
},
{
  "id": 15,
  "name": "Fourth name",
  "parent": 0
},
{
  "id": 25,
  "name": "Fifth name",
  "parent": 5
}
]

I would like to build a tree structure around this using ngFor that supports an unlimited number of children levels.

This is what I have tried so far:

<div *ngFor="let d1 of _dataList">
<ul *ngIf="d1.parent == 0">
    <li>
        {{d1.name}}
        <ul *ngFor="let d2 of _dataList">
            <li *ngIf="d2.parent == d1.id">{{d2.name}}</li>
        </ul>
    </li>
</ul>
</div>

That works, but it's ugly and I have to manually repeat this X-levels down the data and thus leaving a hard-coded limit.

How can one optimize this code to support unlimited levels - and look better?

Answer

lucas picture lucas · Aug 22, 2018

you can have a recusive component, say the component called TreeComponent and the template for TreeComponent will be like this

<div *ngFor="let item of dataList">
  <ul *ngIf="item.parent==parentId">
    <li>{{item.name}}
      <tree [parentId]="item.id" [dataList]="removeCurrentLevelItems(dataList,parentId)"></tree>
    </li>
  </ul>
</div>

check the link here for a live demo