A. Gladkiy
A. Gladkiy

Reputation: 3450

Angular: how to initialize variable inside *ngFor

I have an Angular template:

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

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

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

How can I use internal variable inside Angular template?

Upvotes: 1

Views: 1875

Answers (3)

Segun Adeniji
Segun Adeniji

Reputation: 390

<li *ngFor="let item of list | keyvalue">
    <ng-container *ngTemplateOutlet="list; context: { item: item }"></ng-container>
</li>

<ng-template #list let-rand="rand()">
    <input type="radio" class="form-check-input" [id]="'radio-'+rand" name="field-radio" [value]="item.key">
    <label class="form-check-label" [for]="'radio-'+rand">
   {{ item.key }}
 </label>
</ng-template>

Upvotes: 1

Amirhossein Mehrvarzi
Amirhossein Mehrvarzi

Reputation: 18944

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" class="form-check-input" id="radio-{{random[i]}}" name="field-radio" 
    [value]="item.key">
  <label class="form-check-label" for="radio-{{random[i]}}">
    {{ item.key }}
  </label>
</li>

Upvotes: 1

Segun Adeniji
Segun Adeniji

Reputation: 390

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

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

Upvotes: -1

Related Questions