我正在尝试创建一个formGroup,其中一个控件是一个formArray,它反过来保存表单数组。它应该看起来像这样
this.storageForm = new FormGroup({
FLOOR:new FormControl("", Validators.required), // Will receive only 1 floor
AISEL:new FormControl("", Validators.required), // Will receive only 1 Aisel
STACKS: new FormArray([ new FormArray([]) ]), // Nested FormArray is an array of pallets
});表单是基于从数据库接收的数据动态构建的。下面是示例数据。
{
"FLOOR":
{
"NAME": "FLOOR_1",
"AISEL":
{
"NAME": "AISEL_1",
"STACKS": [
{
"NAME": "STACK_1",
"PALLETS": [
{
"NAME": "PALLET_1"
},
{
"NAME": "PALLET_2"
}
]
},
{
"NAME": "STACK_2",
"PALLETS": [
{
"NAME": "PALLET_3"
},
{
"NAME": "PALLET_4"
}
]
}
]
}
}
}我可以向堆栈添加新的formArrays,但不知道如何添加新的formArray
下面是我尝试过的
this.stacks.forEach((stack,index) =>{
(this.storageForm.get('STACKS') as FormArray).push(new FormArray([]));
if(stack.PALLETS) {
stack.PALLETS.forEach(pallet=>{
((this.allocationForm.get('stackArray') as FormArray)[index]).push(new FormArray([]));
})
}发布于 2021-01-27 18:49:11
我自己编写了解决方案。首先,我创建了表单组,如下所示
this.allocationForm = new FormGroup({
FLOOR:new FormControl("", Validators.required),
AISEL:new FormControl("", Validators.required),
stackArray: new FormArray([]),
});循环遍历堆栈列表并为每个堆栈推送一个formArray。如果堆栈有一个托盘列表,则在堆栈formArray中推送一个formArray,我在托盘上循环并为每个托盘动态推送表单控件
this.stacks.forEach((stack,index)=>{
(this.allocationForm.get('stackArray') as FormArray).push(new FormArray([]));
if(stack.Pallets) {
stack.Pallets.forEach((pallet,index)=>{
((this.allocationForm.get('stackArray') as FormArray)
.controls[index] as FormArray).push(new FormControl(index));
})
}
})这个嵌套看起来像
FormGroup [ FormArray [ FormArray表单控件]]
https://stackoverflow.com/questions/65835691
复制相似问题