如何在Angular *ngFor循环的select标签中独立绑定[(ngModel)] 避免值同步
问题根源
所有下拉框同步变更的核心原因是你在<select>标签上给所有下拉框指定了相同的formControlName="selectStation",所有下拉框都绑定到了同一个FormControl实例,只要任意一个值变更,所有绑定该实例的控件都会同步更新。同时你混用了响应式表单的formControlName和模板驱动表单的[(ngModel)],两种表单API混用也会导致绑定逻辑异常。
解决方法1:使用模板驱动表单(适配现有代码逻辑)
你当前已经用了[(ngModel)]做双向绑定,直接删掉<select>标签中的formControlName="selectStation"属性即可,修改后的<select>代码如下:
<select #selectnow class="form-control bg-light col mr-3" name="selectStation[{{index}}]" size=1 [(ngModel)]="selectStations[index]"> <option selected value="">choose station...</option> <option *ngFor="let station of stations" [value]="station.id" > {{ station.name }} </option> </select>
额外优化:[(ngModel)]已经会自动给selectStations对应下标的位置赋值,你可以删掉(change)绑定和对应的addSelectStation方法,简化代码。
解决方法2:使用响应式表单(更适合动态控件场景)
如果你需要用响应式表单管理,就不要混用[(ngModel)],改用FormArray管理所有下拉框的控件实例:
TS代码修改
import { FormGroup, FormControl, FormArray } from '@angular/forms'; // 声明表单 stationForm: FormGroup; get stationSelectArray(): FormArray { return this.stationForm.get('selectStations') as FormArray; } ngOnInit() { this.stationForm = new FormGroup({ selectStations: new FormArray([]) }); } addSlotSelectStation(){ this.view.loading = true; // 新增FormControl到FormArray this.stationSelectArray.push(new FormControl(null)); this.view.loading = false; } deleteSelectStation(index: number): void{ this.stationSelectArray.removeAt(index); }
HTML代码修改
<ul class="list-group overflow-auto" [formGroup]="stationForm" formArrayName="selectStations"> <li *ngFor="let selectControl of stationSelectArray.controls; let index = index" class="list-group-item" > <div class="form-inline"> <span class="mr-3">{{ index + 1 }}</span> <select class="form-control bg-light col mr-3" [formControlName]="index" size=1 > <option selected value="">choose station...</option> <option *ngFor="let station of stations" [value]="station.id" > {{ station.name }} </option> </select> <div>{{ selectControl.value }}</div> <div>{{ index }}</div> <button class="btn btn-outline-info" (click)="deleteSelectStation(index)" > X </button> </div> </li> </ul>
内容的提问来源于stack exchange,提问作者Sirawit
相关产品推荐
相关产品推荐

