Angular动态表单添加字段报错:Cannot find control with path: 'details -> 0'
问题分析与修复方案
你的错误根源在于FormArray的结构设计错误,以及HTML模板中表单控件的绑定逻辑不匹配:
- 当前的
details是嵌套的FormGroup+FormArray结构,但每个数组项应该是包含label和description的FormGroup,而非单独的FormControl - HTML模板错误地用索引
i作为formControlName,且未为每行设置formGroupName来绑定对应的FormGroup
以下是完整的修改代码:
修改后的TypeScript代码
import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; // 组件类内代码 formMain = this.fb.group({ details: this.fb.array([ // 初始化一行默认数据 this.createDetailFormGroup('label', 'description') ]) }); // 获取details FormArray的快捷方法(模板中会用到) get detailsFormArray(): FormArray { return this.formMain.get('details') as FormArray; } constructor(private fb: FormBuilder) {} // 创建单个详情行的FormGroup createDetailFormGroup(label = '', description = ''): FormGroup { return this.fb.group({ label: [label], description: [description] }); } // 添加新行 increaseDetailRow(): void { this.detailsFormArray.push(this.createDetailFormGroup()); } // 删除指定行 decreaseDetailRow(index: number): void { // 至少保留一行数据 if (this.detailsFormArray.length > 1) { this.detailsFormArray.removeAt(index); } }
修改后的HTML代码
<div [formGroup]="formMain"> <div formArrayName="details"> <div *ngFor="let detail of detailsFormArray.controls; index as i" [formGroupName]="i"> <mat-form-field appearance="fill"> <mat-label>Label of a detail</mat-label> <input matInput type="text" formControlName="label"> </mat-form-field> <mat-form-field appearance="fill"> <mat-label>Description of a detail</mat-label> <input matInput type="text" formControlName="description"> </mat-form-field> <button type="button" *ngIf="detailsFormArray.length > 1" (click)="decreaseDetailRow(i)" mat-fab color="primary" aria-label="Remove a row from the detail list"> <mat-icon>remove</mat-icon> </button> <button type="button" (click)="increaseDetailRow()" mat-fab color="primary" aria-label="Add a new row to the detail list"> <mat-icon>add</mat-icon> </button> </div> </div> </div>
验证最终数据结构
填写表单后,通过this.formMain.value可以得到你期望的结构:
{ "details": [ { "label": "My label 1", "description": "My description 1" }, { "label": "My label 2", "description": "My description 2" } ] }
内容的提问来源于stack exchange,提问作者xRay
相关产品推荐
相关产品推荐

