Search code examples
htmlangularrecursiontreediagram

A recursive function in Angular html document


I need to build a diagram visualy basicaly a family tree: this is what i need :) from an object array that looks like this

[{
Id:1,
child:[
       {id:2,
        child:[
               {id:4,
                child:[]}]
        },
        {id:3,
        child:[]}
        ]
}]

I think my only option to generate the tree is using recursive function in the html component. Is it even possible to make a recursive function using ngfor and ng-template? And how can I do it? Thanks in advance.


Solution

  • Just in case anyone needs to solve exactly the same problem

        <ul>
          <ng-container
            *ngTemplateOutlet="Recursion; context:{ list: List}"
          ></ng-container>
        </ul>
    
    
    
    <ng-template #Recursion let-list="list">
          <li *ngFor="let item of list">
            <a href="#">{{ item.name }}</a>
            <ul *ngIf="item.child.length > 0">
              <ng-container
                *ngTemplateOutlet="Recursion; context:{ list: item.child }"
              ></ng-container>
            </ul>
          </li>
        </ng-template>