我正在尝试使用 Angular ReactiveForms 生成动态表单。目前我收到错误Cannot find control with path 'myFormArray -> [index] -> myProperty
。我已经检查了一些在互联网上找到的答案,但没有成功。这是我的代码:
HTML:
<form [formGroup]="myForm">
<div formArrayName="myFormArray" *ngFor="let ctrl of foo.controls; let i=index">
<div [formGroupName]="i">
<input matInput type="text" formControlName="myProperty">
</div>
</div>
</form>
TS:
export class MyClass implements OnChanges {
@Input() myData: any;
myForm: FormGroup;
get foo(): FormArray{
return <FormArray>this.myForm.get('myFormArray');
}
constructor(private fb: FormBuilder) { }
ngOnChanges() {
if (!this.myForm) {
this.myForm = this.fb.group({
myFormArray: this.fb.array([this.buildMyFormArray()])
});
}
this.myForm.setControl('myFormArray', this.fb.array(myData || []));
}
buildMyFormArray(): FormGroup {
return this.fb.group({
myProperty: ''
});
}
}
myData
来自父组件作为组件的输入,它看起来像
myData: [
{ myProperty: 'John Doe' },
{ myProperty: 'Jane Doe' },
{ myProperty: 'Jack Doe' }
]
更改中间索引的数据数组中的每个项目都会发生错误。
你能帮助我吗?谢谢