angularmat-form-field

Angular drop down giving same value for other two options in mat form


I am trying to get selected option in angular through below code. But when I select 1 drop down option then other two gets same as shown in pic. How can I fix this.

 <div *ngFor="let candidate of candidates">
  <div class="column">
    <mat-form-field appearance="fill" style="max-width: 50px">
      <mat-label></mat-label>
      <mat-select [(ngModel)]="selectedValue" name="preference">
        <mat-option
          *ngFor="let preference of candidate.preferences"
          [value]="preference"
          >{{ preference }}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </div>
  <div class="column">
    {{ candidate.name }}
  </div>
  <div class="column">
    {{ candidate.party }}
  </div>
</div>

enter image description here


Solution

  • Because you need to use the same variable selectedValue. You better define the array of selected values.

    let selectedArray: number[] = candidates.map(_ => 0);
    

    And then, add the index variable in ngFor loop.

    <div *ngFor="let candidate of candidates; index as index">
        <div class="column">
            <mat-form-field appearance="fill" style="max-width: 50px">
                <mat-label></mat-label>
                    <mat-select [(ngModel)]="selectedArray[index]" name="preference">
                        <mat-option
                            *ngFor="let preference of candidate.preferences"
                            [value]="preference"
                        >{{ preference }}
                        </mat-option>
                    </mat-select>
            </mat-form-field>
        </div>
        <div class="column">
            {{ candidate.name }}
        </div>
        <div class="column">
            {{ candidate.party }}
        </div>
    </div>