【发布时间】:2021-10-15 20:51:00
【问题描述】:
我正在使用使用 FormArray 的嵌套 FormControl。我的表格是这样的:
let form = new FormGroup({
name: new FormControl(),
email: new FormControl(),
Addresses : new FormArray([
new FormGroup({
building: new FormControl(),
society : new FormControl(),
}),
new FormGroup({
building: new FormControl(),
society : new FormControl(),
})
new FormGroup({
building: new FormControl(),
society : new FormControl(),
})
])
})
addNewAddress() {
let newAddress = new FormGroup({
building: new FormControl(),
society : new FormControl(),
});
this.form.get("addresses").push(newAddress)
}
在 HTML 模板中
<div *ngFor="let controlGroup of form.get('addresses').controls; let i=index">
<ng-container [formGroup]="controlGroup">
<input type="text" formControlName="building" />
<input type="text" formControlName="society" />
</ng-container>
</div>
**但是上面的代码返回Build Error,就像abstractControl上不存在控件一样。 **
所以我使用这个 getter Melthod 将 form.get('addresses') 转换为 FormControl。
get addressArray() : FormArray {
return form.get('addresses') as FormArray
}
//And use it in HTML like this
<div *ngFor="let controlGroup of addressArray.controls; let i=index">
<ng-container [formGroup]="controlGroup"> <== now here is build error
<input type="text" formControlName="building" />
<input type="text" formControlName="society" />
</ng-container>
</div>
转换之后。新的构建错误引发controlGroup does not contain this methods : addControl, removeCotnrol and ...
因为addressArray.**controls** 返回abstractControl 的数组而不是FormControl 和[formGroup] 指令需要FormControl。
我怎样才能像这样在*ngFor 中定义类型:
let (controlGroup: FormControl) of addressArray.controls; let i=index
这可能吗?
请帮帮我。
【问题讨论】:
-
1.- formControlName not 包含在
[]-else 角度搜索名为 building- 的变量。 2.- 你应该使用[formGroupName]="i"而不是[formGroup]="controlGroup" -
哦,是的,这是一个书面错误。我的代码不包含
[ ]。
标签: angular formarray formgroups angular-abstract-control