Jesper
Jesper

Reputation: 2804

Getting values from select elements in *ngFor

Let's say I have this template:

<div *ngFor="let div of divs">
  <select #ref (change)="print(ref)">
    <option *ngFor = "let opt of options">{{opt}}</option>
  </select>
</div>

and this component:

export class AppComponent {
  divs = ["1", "2", "3"];
  options = ["opt1", "opt2", "opt3"];

  print(value){
    console.log(value.value);
  };
}

Now I can get the value of each individual select element whenever a new option is selected. However, with this method I'm creating a template reference variable on the select (#ref) in the *ngFor loop, which means I will have 3 selects with the same reference at the end of the loop. It says the following on the angular.io website:

"Do not define the same variable name more than once in the same template. The runtime value will be unpredictable."

Therefore, I'm assuming it's a bad idea to use this method. My question is if there is another way to do this?

Upvotes: 4

Views: 8417

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58573

I don't think, there is need of local varible just for getting selected values :

Just use (change)="print($event.target.value)" and [value]='opt'

<div *ngFor="let div of divs">
  <select (change)="print(div ,$event.target.value)">
    <option *ngFor = "let opt of options" [value]='opt'>{{opt}}</option>
  </select>
</div>

print(value_of , value) {
   console.log('value of' , value_of , 'is' , value );
}

Upvotes: 1

Related Questions