如何绑定Angular动态表单?FormArray绑定输入框报属性不存在错误如何解决
错误原因
- 模板中直接使用
items变量,但你的组件类没有定义该成员属性。items是itemsForm表单组下的FormArray子控件,模板无法直接访问。 - 表单项绑定逻辑错误:循环得到的
item是FormGroup实例,不能直接用item.x作为formControlName的绑定值,formControlName需要对应FormGroup内的控件名字符串。
解决方案
步骤1:修改TS组件代码
添加一个getter用来暴露items FormArray,解决模板找不到属性的问题:
// 新增getter,注意需要从@angular/forms导入FormArray类型 get items(): FormArray { return this.itemsForm.get('items') as FormArray; } // 原有代码保持不变即可 itemFormGroup = new FormGroup({ x: new FormControl(4), y: new FormControl(1), z: new FormControl(0), }); itemsForm = new FormGroup({ items: new FormArray([ this.itemFormGroup ]) });
如果不想加getter,也可以直接在模板里写itemsForm.controls.items.controls访问,但是加getter的写法更简洁,类型校验也更安全。
步骤2:修改HTML模板代码
循环行添加[formGroupName]="i"绑定FormArray的索引,formControlName直接写对应控件名的字符串:
<table class="table table-borderless" [formGroup]="itemsForm"> <thead> <tr> <th>x</th> <th>y</th> <th>z</th> </tr> </thead> <tbody formArrayName="items"> <tr *ngFor="let item of items.controls; let i=index" [formGroupName]="i"> <td><input type="text" class="form-control form-control-sm" formControlName="x"></td> <td><input type="text" class="form-control form-control-sm" formControlName="y"></td> <td><input type="text" class="form-control form-control-sm" formControlName="z" disabled></td> </tr> </tbody> </table>
内容的提问来源于stack exchange,提问作者barteloma
相关产品推荐
相关产品推荐

