如何解决填充表单数组
各位晚安, 我有以下问题来填充表单数组,我设法将代码开发到一个步骤,但现在我陷入了一个步骤。 我设法使用 setControl 填充数组,但现在我需要在该数组中填充一个数组,但遇到了很多麻烦。 我能够填充 feedstock 数组,但无法填充 feedstockOptions 数组 按照下面的代码:
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,你可以用“map”代替 forEach 和 push。 “map”数组函数将一个数组转换为另一个数组。
例如
//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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。