Angular FormArray中Input序号添加新行后未更新的问题
Angular FormArray 新增行时序号无法更新的解决方法
问题场景
在使用Angular响应式表单的FormArray时,新增行后,绑定到operational_sequence_no的输入框序号始终显示为1,无法随行索引更新。直接使用value="{{i+1}}"、[value]="i+1"等写法无效,用[ngModel]="i+1"能正常显示但控制台提示该写法已废弃。
原因分析
- 当输入框同时设置
formControlName和value属性时,表单控件的value会覆盖value属性的静态设置,且value是单向绑定,不会随索引变化自动更新。 [ngModel]与formControlName混用属于模板驱动表单和响应式表单的混合写法,当前Angular版本已标记该方式为废弃。
解决方案
方案1:通过组件类维护并更新序号(推荐)
在新增或删除行时,手动更新FormArray中每个控件的operational_sequence_no值,确保序号与行索引同步。
组件类代码示例:
// 新增行方法 addRow() { const arithmeticItems = this.PreprocessingForm.get('arithmeticItems') as FormArray; arithmeticItems.push(this.createNewRow()); // createNewRow需返回新的FormGroup实例 this.updateSequenceNumbers(); } // 删除行方法 deleteRow(index: number) { const arithmeticItems = this.PreprocessingForm.get('arithmeticItems') as FormArray; arithmeticItems.removeAt(index); this.updateSequenceNumbers(); } // 更新所有行的序号 private updateSequenceNumbers() { const arithmeticItems = this.PreprocessingForm.get('arithmeticItems') as FormArray; arithmeticItems.controls.forEach((control, index) => { control.patchValue({ operational_sequence_no: index + 1 }); }); }
模板代码调整(移除多余的value/ngModel,仅保留formControlName):
<tr class="mat-row" *ngFor="let dynamic of PreprocessingForm.controls.arithmeticItems['controls']; let i = index" [formGroupName]="i"> <td> {{ i+1 }} </td> <td class="mat-cell"> <mat-form-field appearance="outline" style="width: 4rem;text-align: center;"> <input matInput formControlName="operational_sequence_no" type="text" readonly> </mat-form-field> </td> </tr>
方案2:纯展示场景(无需提交序号)
如果operational_sequence_no仅用于展示,不需要提交到后端,可以移除formControlName,直接绑定[value]:
<input matInput type="text" [value]="i+1" readonly>
内容的提问来源于stack exchange,提问作者Purushottam Nawale
相关产品推荐
相关产品推荐

