Search code examples
angularngforangular-ngmodel

Using ngModel inside an ngFor loop


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


Solution

  • An easy solution is to bind the selected option to the group as follows.

    1. Create a new interface:

      interface Group { name: string; selectedOption?: string; }

    2. Change the groups' type to an array of Group:

      groups: Group[] = [{ name: "Group1" }, { name: "Group2" }];

    3. Change the ngModel binding:

      <select [(ngModel)]="group.selectedOption">

    You can find my solution here