Home > Enterprise >  How to render all subarrays elements of array in Angular?
How to render all subarrays elements of array in Angular?

Time:04-10

I have an array like this:

type categories = {
  name: string;
  sub?: categories[];
};

categories: Array<categories> =
[{ name: 'C1',
      sub: [{name: 'S1',
        },
        {name: 'S2',
          sub: [{ name: 'SS1',
               sub: [{ name: 'SSS1',
                },
                { name: 'SSS2',
                },],
          },],
      },],
},];

Every sub can have unlimited subs. How can I render all elements of all subarrays?

Thank you!

CodePudding user response:

You can recursively nest components like so:

@Component({
  selector: 'example-component',
  template: `
    <div *ngFor="let nestedCategory of nestedCategories.sub">
      <div>{{nestedCategory.name}}</div>
      <div *ngIf="nestedCategory.sub">
        <example-component [nestedCategories]="nestedCategory.sub"></example-component>
      </div>
    </div>
  `
})
export class ExampleComponent {
  @Input('nestedCategories') nestedCategories!: Array<categories>;
}

Then in your parent component template you can declare it as follows:

<example-component [nestedCategories]="categories"></example-component>
  • Related