I'm working on a little project in Angular2 (I'm a beginner).
Basically it involves an array and up to three Material Angular Select forms to pick values from it.
Here is the plunker : https://plnkr.co/edit/700zL1tDxml0zQwF6yj6?p=preview
JS code
this.udlsCarac={ "Ticker1": { "NAME": "Name 1" }, "Ticker2": { "NAME": "Name 2" }, "Ticker3": { "NAME": "Name 3" } };
this.udlsTickers = Object.keys(this.udlsCarac);
this.udls=[];
this.udls.push(this.udlsTickers[0]);
this.nbUdls=1;
this.nbUdlsMax=3;
addUdlSelector(){
this.udls.push(this.udlsTickers[0]);
this.nbUdls+=1;
}
removeUdlSelector(){
this.udls.pop();
this.nbUdls-=1;
}
HTML code
<div *ngFor="let u of udls; let i=index">
<md-select [(ngModel)]="udls[i]" name="choice">
<md-option *ngFor="let udl of udlsTickers" [value]="udl">
{{udlsCarac[udl].NAME}}
</md-option>
</md-select>
</div>
How to replicate the issue
1 - Select Name 2 or Name 3 on 1st Select
2 - Click "+" button to add a new Select
3 - you can see that the Array of selected values (this.udls
) is correct but the value of 1st Select has switched to Name 1
Could you please give me some help? thanks a lot !
When using name
in forms every name has to be unique, otherwise the same value will be applied to all. In your iteration, all end up with the same name, ie. name="choice"
So make choice unique by adding your index.
name="choice{{i}}"
and it will work as you want :)