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

Time:05-14

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 >
    <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 >
    {{ candidate.name }}
  </div>
  <div >
    {{ candidate.party }}
  </div>
</div>

enter image description here

CodePudding user response:

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 >
        <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 >
        {{ candidate.name }}
    </div>
    <div >
        {{ candidate.party }}
    </div>
</div>
  • Related