Home > database >  Iterate over nested object with array of children
Iterate over nested object with array of children

Time:03-21

I am trying to iterate using Angular TS over a nested object structured like that:

{
  "stringKey1": {
    "child": [
      {
        "stringKey2": {
          "child": []
        }
      },
      {
        "stringKey3": {
          "child": []
        }
      },
      {
        "stringKey4": {
          "child": [
            {
              "stringKey5": {
                "child": []
              }
            },
            {
              "stringKey6": {
                "child": []
              }
            }
          ]
        }
      }
    ]
  }
}

Basically each "node" is composed by a string Key and a object {"child" : []} that can have many children with the same structure.

I tried *ngFor with pipe, tried *ngIf to check if it is an array, but I can´t managed to make it work. It´s not possible to know how deep is the structure.

Basically a tried anything I have seen in the internet but I might be missing something.

Any help?

Thanks a lot.

CodePudding user response:

I would avoid excess template logic that comes with nested object for-looping. It's hard to read and debug. Instead, simplify data in TS code if possible. And then manipulate it in template.

But we can make of use | keyvalue pipe to iterate over Objects with *ngFor. We then use ng-template and *ngTemplateOutlet to create recursion.

<ng-template #recursiveList let-array>
  <li *ngFor="let item of array | keyvalue">
    {{item.key}} {{item.value}}
    <ul *ngIf="item.value"> 
      <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.value }"></ng-container>
    </ul>
  </li>
</ng-template>

<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: object }"></ng-container>

Here is a working example: https://stackblitz.com/edit/angular-nested-ngfor-in-table-4nqhve?file=src/app/app.component.html

  • Related