0

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.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • Please see if this can help you: https://stackoverflow.com/questions/35733186/angular2-ul-li-json-tree-recursive-in-ngfor. It shows how you can iterate an object recursively, using ngTemplate. – DGR Mar 20 '22 at 00:00

1 Answers1

3

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%2Fapp%2Fapp.component.html

Joosep Parts
  • 5,372
  • 2
  • 8
  • 33