Angular報錯:ERROR TypeError: control.setParent is not a function
這裏是定義的 myForm ,字段 imageIds 爲數組:
myForm = this.fb.group({
id: [''],
title: [''],
content: [''],
imageIds: this.fb.array(['']),
});
從詳情接口取回數據後,填充到表單裏的 imageIds 字段裏報錯。
let imageIds = this.detail.imageIds;
let newIds = this.myForm.get('imageIds') as FormArray;
if (imageIds) {
let key : any;
for(key in imageIds) {
// <-- ERROR TypeError: control.setParent is not a function
newIds.push(imageIds[key]);
}
}
this.noteForm.patchValue({
id: this.detail.id,
title: this.detail.title,
imageIds: newIds.value, // <---- 補充數據
});
錯誤原因: newIds 是表單組件裏的 FormArray 格式,因此push進去的值也應該是 FormControl 格式。 使用 new FormControl(imageIds[key]) 即可。
let imageIds = this.detail.imageIds;
let newIds = this.myForm.get('imageIds') as FormArray;
if (imageIds) {
let key : any;
for(key in imageIds) {
// <-- 使用 new FormControl()
newIds.push(new FormControl(imageIds[key]));
}
}
this.noteForm.patchValue({
id: this.detail.id,
title: this.detail.title,
imageIds: newIds.value, // <---- 補充數據
});
參考內容:
https://blog.csdn.net/u011763994/article/details/78682576
https://stackoverflow.com/questions/51209125/control-setparent-is-not-a-function-when-dymanically-creating-formgroup
關於關注公衆號【Web後端技術】獲取更多技術知識~