Search code examples
angularangular2-template

Recursive template inside inner @for in Angular 17


I'm trying to create a recursive template an ran into a problem. My template:

<ng-template #recursiveGroups let-groups>
  @for (group of groups; track group; let i = $index) {
      <!-- Some stuff are shown -->
      @for (subGroup of group.subGroups; track subGroup;  let j = $index) {
        <ng-container *ngTemplateOutlet="recursiveGroups; context:{$implicit: data[i].subGroups[j]}"></ng-container>
        <!-- ALSO, SEPARATLY, TRIED: -->
        <ng-container *ngTemplateOutlet="recursiveGroups; context:{$implicit: subGroup}"></ng-container>
        <!-- OR: -->
        <ng-container *ngTemplateOutlet="recursiveGroups; context:{groups: subGroup}"></ng-container>
      }
  }
 </ng-template>
<ng-container *ngTemplateOutlet="recursiveGroups; context:{$implicit: data}"></ng-container>

My data looks like:

data: [
  {
    ...,
    children: [
      {
        ...
      }
    ],
    subGroups: [
      {
        ...,
        children: [
          {
            ...
          }
        ],
        subGroups: [
          {
            ...,
          }
        ],
      }
    ],
  },
  ...
]

Using context:{groups: <*>} shows only the top most level.

Using context:{@implicit: <*>} shows only the top most level and also raises error:

core.mjs:6531 ERROR TypeError: newCollection[Symbol.iterator] is not a function

What am I missing here? Thanks.


Solution

  • Your recursiveGroups template expects an array, hence I don't see you need a nested @for for the subGroups. The template can be reused for the subGroups iteration.

    Changes:

    1. Remove the nested @for.

    2. Provide the group.subGroups to the context for the nested <ng-container>.

    <ng-template #recursiveGroups let-groups>
      @for (group of groups; track group; let i = $index) {
        
        <ng-container *ngTemplateOutlet="recursiveGroups; context:{ $implicit: group.subGroups }"></ng-container>
      }
    </ng-template>
    

    Demo @ StackBlitz