Angular中*ngFor生成的多个input输入时内容同步变更如何修复
问题原因
所有循环生成的输入框都绑定了同一个全局Note变量和同一个form表单实例,任意输入框的值变更都会同步到所有绑定了相同变量/表单实例的输入框上,同时代码混用了响应式表单formControlName和模板驱动表单[(ngModel)],也容易引发绑定冲突。
修复方案
方案1:轻量场景(无需全局表单管理,仅提交时取值)
无需定义全局表单和Note变量,直接通过模板变量获取当前输入框的值提交即可。
TS代码修改
// 移除全局Note变量和ngOnInit中的单表单初始化逻辑 onSubmit(id:number, noteValue:string) { const obj = { Note: noteValue }; console.log(noteValue); this.LExamenSousCategorieService .updateSouCategorie(obj, id) .then(res => {}); }
模板代码修改
<mat-expansion-panel class="childPanel" [expanded]="true" hideToggle disabled style="background:#F2EDFF;" *ngFor="let i of listSousCategorie"> <div class="childPanel_body2 mat-badge-large" fxLayout="row" fxFlex fxLayoutAlign="start center"> <div style="padding-left:1em" fxFlex="grow">{{i.libelle}} {{i.id}}</div> <mat-form-field> <form (ngSubmit)="onSubmit(i.id, noteInput.value)"> <mat-label>Note</mat-label> <input type="text" matInput #noteInput> </form> </mat-form-field> </div> </mat-expansion-panel>
方案2:响应式表单场景(需要对输入做校验/全局管理)
使用FormArray为每个分类项生成独立的表单控件,避免所有输入共享同一个表单实例。
TS代码修改
import { FormArray, FormControl } from '@angular/forms'; // 移除全局Note变量 noteFormArray: FormArray; ngOnInit() { // 为每一个分类项生成独立的表单控件 this.noteFormArray = this.formBuilder.array( this.listSousCategorie.map(() => new FormControl('')) ); } onSubmit(id:number, index:number) { const noteValue = this.noteFormArray.at(index).value; const obj = { Note: noteValue }; console.log(noteValue); this.LExamenSousCategorieService .updateSouCategorie(obj, id) .then(res => {}); }
模板代码修改
<mat-expansion-panel class="childPanel" [expanded]="true" hideToggle disabled style="background:#F2EDFF;" *ngFor="let i of listSousCategorie; let index = index"> <div class="childPanel_body2 mat-badge-large" fxLayout="row" fxFlex fxLayoutAlign="start center"> <div style="padding-left:1em" fxFlex="grow">{{i.libelle}} {{i.id}}</div> <mat-form-field> <form [formGroup]="noteFormArray.at(index)" (ngSubmit)="onSubmit(i.id, index)"> <mat-label>Note</mat-label> <input type="text" matInput formControlName="Note"> </form> </mat-form-field> </div> </mat-expansion-panel>
注意事项
Angular官方不推荐同时混用响应式表单的formControlName和模板驱动表单的[(ngModel)],两种表单模式选其一使用即可,避免出现未知的绑定异常。
内容的提问来源于stack exchange,提问作者drnwork
相关产品推荐
相关产品推荐

