晚安,各位,我在填充表单数组时遇到了以下问题,我设法开发了一个步骤的代码,但现在我陷入了困境。我设法使用setControl填充了数组,但现在我需要在这个数组中填充一个数组,我遇到了很多麻烦。我能够填充原料阵列,但无法填充原料选项阵列遵循以下代码:
Method populate form
if (response.feedstocks?.length >=1 && response.feedstocks != null) {
this.feedstockForm.setControl('feedstock', this.editFeedstock(response.feedstocks))
}
editFeedstock(response) {
const formArray = new FormArray ([]);
response.forEach (s => {
formArray.push ( this.fb.group ({
category: s.category,
position: s.position,
feedstockOptions: s.feedstockOptions (//this.editFormOptions(s.feedstockOptions))
}));
});
return formArray;
}
editFormOptions(response) {
const array = new FormArray([]);
response.forEach(r => {
array.push(this.fb.group({
feedstockOptions: r.feedstockOptions
}))
})
console.log(response)
return array
}
Form
feedstockForm: FormGroup = this.fb.group({
feedstock: this.fb.array([
this.feedstockFormsCategory()
])
});
feedstockFormsCategory(): FormGroup {
return this.fb.group({
category: "",
position: "",
feedstockOptions: this.fb.array([
this.feedstockFormsComponent()
])
})
};
feedstockFormsComponent(): FormGroup {
return this.fb.group({
name: '',
code: '',
price: this.fb.group({
amount: ['', Validators.required],
currency: ['BRL'],
}),
})
};
Rod,您可以使用"地图";而不是forEach和push。";地图";数组函数将一个数组转换为另一个数组。
例如
//Is the same
const formArray = new FormArray ([]);
response.forEach (s => {
formArray.push (
this.fb.group ({
category: s.category,
position: s.position)
});
return formArray;
//that
return response.map(s=>{
return this.fb.group ({
category: s.category,
position: s.position,)
});
})
看到我们用数组的值转换FormGroup数组中的对象数组
好吧,当你制作创建表单的函数时,你可以传递一个对象作为参数"可选";。因此,您的函数feedstockFormsCategory和feedstockFormsComponent变得类似。
feedstockFormsCategory(data:any=null): FormGroup {
data=data || {category:'',position:'',feedstockOptions:null}
return this.fb.group({
category:data.category,
position: data.position,
feedstockOptions: data.feedstockOptions?this.fb.array(
data.feedstockOptions.map(x=>this.feedstockFormsComponent(x))):
this.fb.array([]) //a empty array
//you can also return an array with one element
//if you use
//this.fb.array([this.feedstockFormsComponent()])
])
})
};
feedstockFormsComponent(data:any=null): FormGroup {
data=data|| {name:'',code:'',price:{amount:'',currency:'BRL'}}
return this.fb.group({
name: data.name,
code: data.code,
price: this.fb.group({
amount: [data.price.amount, Validators.required],
currency: [data.price.currency],
}),
})
};
请注意,您可以使用仅的响应值创建FormArray
this.formArray=this.fb.array(response.map(x=>this.feedstockFormsCategory(x))