Home > Enterprise >  Angular: How to use *ngFor with an array which has a dynamic name?
Angular: How to use *ngFor with an array which has a dynamic name?

Time:10-14

I have some arrays dynamically named sub_0, sub_1, sub_2 etc. I want to use them with *ngFor but I could not find a way to call them. Not sure if there is a way to do it.

i is a dynamic number, I tried

<a class="link" href="#" *ngFor="let sub of sub_ i" > </a>
<a class="link" href="#" *ngFor="let sub of sub_ {{i}}" > </a>
<a class="link" href="#" *ngFor="let sub of sub_$i" > </a>

but none of them worked.

CodePudding user response:

I guess it should be the same as you use in TS code:

*ngFor="let sub of this['sub_'   i]">

CodePudding user response:

It is easier to handle dynamic logic in the typescript side.

// component.ts
const N = 10;
const arrays = Array.from(Array(N).keys()).map(i => `sub_${i}`);

// component.html
<ng-container *ngFor="let array of arrays">
  <a class="link" href="#" *ngFor="let sub of array" > </a>
</ng-container>
  • Related