Angular 下拉为垫形式的其他两个选项提供相同的值

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

我正在尝试通过以下代码在 angular 中获取 selected 选项。但是当我 select 1 下拉选项然后其他两个变得相同,如图所示。我该如何解决这个问题。

 <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>

因为你需要使用同一个变量selectedValue。您最好定义所选值的数组。

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

然后,在 ngFor 循环中添加索引变量。

<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>