I am using ngModel
inside of an ngFor
loop to get values from a dropdown menu, like so:
<div *ngFor="let group of groups">
<select [(ngModel)]="selectedOption">
<option *ngFor="let o of options">
{{o.name}}
</option>
</select>
<p>Selected option: {{ selectedOption }}</p>
<div>
When I pick a selection from the dropdown, it sets all the other dropdowns to the same value. This is expected behavior, since ngModel
is bound to selectedOption
on all the instances created by the ngFor
loop.
My question is, what is a good method for uncoupling different dropdowns within a loop so that they act independently?
Stackblitz is here
An easy solution is to bind the selected option to the group as follows.
Create a new interface:
interface Group { name: string; selectedOption?: string; }
Change the groups' type to an array of Group:
groups: Group[] = [{ name: "Group1" }, { name: "Group2" }];
Change the ngModel binding:
<select [(ngModel)]="group.selectedOption">
You can find my solution here