You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中通过ngFor索引绑定数组元素到mat-select出现异常如何解决

问题原因

这不是Angular Material的缺陷,是代码编写错误导致的:
你在循环生成的所有mat-select组件上使用了相同的name="countryString"属性。Angular表单机制中,使用ngModel且绑定name属性时,会将相同name的控件识别为同一个表单字段,因此视图层会出现选中一个所有同name控件同步更新的现象,但实际上你绑定的数组取值是按索引区分的,所以数组第二个元素不会被实际赋值。

解决方案

有两种常用修复方式,任选一种即可:

方式1:设置唯一的name属性

将name属性和循环索引绑定,保证每个mat-select的name值唯一:

<div *ngFor="let f of fields; let i = index">
  <mat-form-field>
    <mat-select [name]="'countryString' + i" [(ngModel)]="fields[i]" placeholder="Country">
      <mat-option *ngFor="let item of countries" [value]="item.short">{{item.full}}</mat-option>
    </mat-select>
  </mat-form-field>
</div>

方式2:设置ngModel为独立模式

如果你不需要使用Angular表单的整体提交、校验能力,可以给ngModel设置独立模式,跳过和name属性的关联:

<div *ngFor="let f of fields; let i = index">
  <mat-form-field>
    <mat-select name="countryString" [(ngModel)]="fields[i]" [ngModelOptions]="{standalone: true}" placeholder="Country">
      <mat-option *ngFor="let item of countries" [value]="item.short">{{item.full}}</mat-option>
    </mat-select>
  </mat-form-field>
</div>

内容的提问来源于stack exchange,提问作者turanszkik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 03:57:02