如何修补 angular 中另一个表单数组内部的嵌套表单数组中的值?

How to patch value in nested form array which is insider another form array in angular?

我目前正在使用表单数组处理此嵌套表单。所以,我在 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 的一些方法如下:

  1. this.userEditForm.patchValue(user); //user is object received from server. I tried to patch response directly but it did not worked.

  2. 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 中,将表单数组嵌套在其他表单数组中的深层嵌套表单中修补值的正确方法是什么?我究竟做错了什么?或如何为嵌套表单数组正确完成该补丁。我现在被困在这几天了。非常感谢任何类型的建议或解决方案或我所缺少的东西。提前致谢。

FormArray needs controls(groups) inside it to patch.

最初,carsdates 是带有 1 个 FormGroup 的 FormArray。如果您尝试将响应直接修补到 userEditForm 并控制 userEditForm.value,您会发现 1 个值已正确修补。

因此,对于嵌套的 response(user) 数组中的每个值,您需要创建一个 FormGroup 然后为其修补值

let vehicles = user.vehicles;
    (this.userEditForm.get('vehicles') as FormArray).clear(); //Removing initial item b/c you are creating form array with 1 initial value
    vehicles.forEach((car) => {
      const vehicleForm = this.createVehiclesForm();
      vehicleForm.patchValue(car); //Patch each vehicle object, but it will not patch the nested cars & dates FormArray.

      //Create Cars FormArray individually & patch the value
      (vehicleForm.get('cars') as FormArray).clear(); //To remove initial value
      car.cars.forEach((item) => {
        const carForm = this.createCarsForm();
        carForm.patchValue(item); //Patch individual cars item
        (vehicleForm.get('cars') as FormArray).push(carForm);
      });

      //Dates
      (vehicleForm.get('dates') as FormArray).clear();
      car.dates.forEach((item) => {
        const dateForm = this.createDatesForm();
        dateForm.patchValue(item);
        (vehicleForm.get('dates') as FormArray).push(dateForm);
      });
      (this.userEditForm.get('vehicles') as FormArray).push(vehicleForm); //Finally, push the
    });

工作示例:https://stackblitz.com/edit/angular-4vbrzj?file=src/app/app.component.ts