Recursive HTML template in Angular

Recursive html template inside the one component.

Published: 6/8/2024

The first container calls the template with some data, and the template keeps calling itself on nested data as required.

Additionally, the formGroup param is being passed through each time.

<ng-container *ngTemplateOutlet="Recursion; context: { formGroup: form, formSchemaItems: formSchema?.ui?.items }"></ng-container>

<ng-template #Recursion let-formGroup="formGroup" let-formItems="formSchemaItems">
  <ng-container *ngFor="let item of formItems">
    <div *ngIf="someWrapper">
      <!-- Call the template again -->
      <ng-container *ngTemplateOutlet="Recursion; context: { formGroup: formGroup, formSchemaItems: item.items }"></ng-container>
    </div>
    <div *ngIf="someOtherWrapper">
      <!-- Call the template again -->
      <ng-container *ngTemplateOutlet="Recursion; context: { formGroup: formGroup, formSchemaItems: item.items }"></ng-container>
    </div>
  </ng-container>
</ng-template>