【发布时间】:2022-02-02 01:45:12
【问题描述】:
我目前正在使用表单数组处理这个嵌套表单。所以,我在editUser.ts文件中创建了如下表单:
userEditForm : FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit(): void {
this.createUserEditForm();
}
createUserEditForm() {
this.userEditForm = this.fb.group(
{
userId: new FormControl(null),
userName:new FormControl(null, Validators.required),
address: new FormControl(null),
vehicles: this.fb.array([this.createVehiclesForm()])
}
);
}
createVehiclesForm(): FormGroup {
return this.fb.group({
vehicleId: new FormControl(null),
vehicleType:new FormControl(null),
cars: new FormArray([this.createCarsForm()])
dates:new FormArray([this.createDatesForm()])
})
}
createCarsForm(): FormGroup {
return this.fb.group({
carId: new FormControl(null),
name: new FormControl(null)
})
}
createDatesForm(): FormGroup {
return this.fb.group({
id:new FormControl(null),
boughtDate: new FormControl(null)
})
}
我从服务器收到以下 json 响应作为用户对象:
{
"userId": "c005",
"userName": "Charlie",
"address": "London",
"vehicles": [{
"vehicleId": 19,
"vehicleType":"Four Wheeler",
"cars": [{
"carId": 20,
"name": "BMW"
},
{
"carId": 21,
"name": "Audi"
},
{
"carId": 22,
"name": "RangeRover"
}
],
"dates": [{
"id": 23,
"boughtDate": "2022-02-01"
}]
}]
}
我要解决的问题是什么?
用户对象有车辆列表,里面有另一个汽车列表 carId 和里面的名字。我正在尝试创建一个编辑功能,在该功能中我得到了来自服务器的 json 响应,并尝试将其修补到用户对象。
我尝试将数据修补到我的 userEditForm 的一些方法如下:
-
this.userEditForm.patchValue(user); //user is object received from server. I tried to patch response directly but it did not worked. -
user //从服务器接收到的对象 this.userEditForm.patchValue({ 用户 ID:user.userId, 用户名:user.userName, 地址:user.address });
let vehicles = user.vehicles; const formArray = new FormArray([]); vehicles.forEach(car => { formArray.push(this.fb.group({ vehicleId: car.vehicleId, vehicleType: car.vehicleType, **cars: car.cars//** //I am not able to patch this cars list inside vehicles **dates : car.dates** //same for this date list as well })) }); this.userEditForm.setControl('vehicles', formArray);
我在第 2 点为除汽车和日期之外的所有字段的补丁值尝试过的方法。那么,如何在这种情况下修补车内的汽车或日期。什么是修补深度嵌套形式的值的正确方法,其中表单数组以角度嵌套在其他表单数组中?我究竟做错了什么?或如何为嵌套表单数组正确完成该补丁。我现在被困在这几天了。非常感谢任何类型的建议或解决方案或我缺少的东西。提前致谢。
【问题讨论】:
标签: angular typescript angular-reactive-forms formarray