Angular 2: recursive template for child

The API I'm working with 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 , which supports an unlimited number of levels of children.

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> 

This works, but it is ugly, and I have to manually repeat these X-levels down the data and thus leaving a hard-coded limit.

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

+5
source share

Source: https://habr.com/ru/post/1263587/


All Articles