我有一个表格,它在3秒钟的延迟后可以正常工作。在这3秒钟内,表单中充满了错误,共有15条说明
formGroup expects a FormGroup instance. Please pass one
Cannot read property 'get' of undefined
我了解的是,表单填充基于以下事实:API调用成功并且返回了响应。虽然没有响应,但未定义表单,因此没有错误。
问题:如何摆脱这个问题以及最好的解决方法
HTML模板
<div [formGroup]="productForm">
<div class="r-package-list" formArrayName="packages">
<div
class="r-package-list-item"
*ngFor="let package of packageForms.controls; let i = index"
[formGroupName]="i"
>
<div class="formArrayControlDiv">
<label class="Package-Name-Label"
><input
type="checkbox"
class="Package-Selection-Checkbox"
formControlName="packageCheckBox"
/>
</label>
<input
type="number"
formControlName="packageQuantity"
/>
<input
readonly
type="text"
formControlName="packagePrice"
/>
</div>
</div>
</div>
</div>
TS文件
ngOnInit() {
this.apiService.getPackages(id).then((result: any) => {
this.createForm(result.data);
});
}
// Creating a Product Form
createForm(data) {
const arr = [];
for (let i = 0; i < data.length; i++) {
arr.push(this.packageArrayFunction(data[i]));
}
this.productForm = this.fb.group({
packages: this.fb.array(arr)
});
}
// Creating a Dynamic Package Array
packageArrayFunction(packages): FormGroup {
return this.fb.group({
packageCheckBox: [false],
packageQuantity: [''],
packagePrice: [packages.basic_price + '/' + packages.base_unit]
});
}
get packageForms() {
return this.productForm.get('packages') as FormArray;
}