【问题标题】:How to patch value in nested form array which is insider another form array in angular?如何修补嵌套表单数组中的值,该数组是另一个表单数组的内部角度?
【发布时间】: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 的一些方法如下:

  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 typescript angular-reactive-forms formarray


    【解决方案1】:

    FormArray 需要内部的控件(组)来修补。

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

    https://stackoverflow.com/a/70132244/10602679

    因此,对于 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

    【讨论】:

    • 正如@Pankaj 上面提到的,我没有在表单数组中设置控件。它就像魅力一样。谢谢!!!
    猜你喜欢
    • 2021-12-02
    • 2019-05-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2021-04-06
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多