Home > Mobile >  Angular: how to initialize variable inside *ngFor
Angular: how to initialize variable inside *ngFor

Time:02-14

I have an Angular template:

<li *ngFor="let item of list | keyvalue" let-rand="random()">
  <input type="radio"  id="radio-{{rand}}" name="field-radio" 
    [value]="item.key">
  <label  for="radio-{{rand}}">
    {{ item.key }}
  </label>
</li>

I want to execute rand() function for every iteration of loop. But I get an error:

Property 'rand' does not exist on type...

How can I use internal variable inside Angular template?

CodePudding user response:

<li *ngFor="let item of list | keyvalue; let i= index" >
  <input type="radio"  [id]="'radio-' i" name="field-radio" 
    [value]="item.key">
  <label  [for]="'radio-' i">
    {{ item.key }}
  </label>
</li>

Try to use index, it will give you unique identifier on id and for attributes

CodePudding user response:

You can't create a custom local variable within a ngFor. You can only use the exported values that can be aliased to local variables. Perhaps, you need another array of random numbers to use in your iteration at the same time like bellow :

<li *ngFor="let item of list | keyvalue; let i = index">
  <input type="radio"  id="radio-{{random[i]}}" name="field-radio" 
    [value]="item.key">
  <label  for="radio-{{random[i]}}">
    {{ item.key }}
  </label>
</li>

CodePudding user response:

<li *ngFor="let item of list | keyvalue" >
 <ng-template #introText let-title="title" let-rand="rand()">
   <input type="radio"  [id]="'radio-' rand" name="field-radio" 
    [value]="item.key">
  <label  [for]="'radio-' rand">
    {{ item.key }}
  </label>
</ng-template>

</li>

"let-" is only supported on ng-template elements.

  • Related