首页 > 解决方案 > 反应形式角度添加新控件

问题描述

我正在尝试在数组中的表单上添加新的表单控件,但我遇到的问题是我总是空控件,即使我在数组中有一些值

这就是我现在所拥有的

 this.userVehicles= [];
 this.userVehicles= [{Model: 'Fiat', RegistrationPlate: 'Taxi', LastServiceDate: 'Nov 11', Vin: '111', YearManufacture: '2015'}];

const vehicleFGs: any = this.userVehicles.map(vehicle => this._fb.group({
      Model: [vehicle.model],
      RegistrationPlate: [vehicle.registrationPlate],
      LastServiceDate: [vehicle.lastServiceDate],
      Vin: [vehicle.vin],
      YearManufacture: [vehicle.yearManufacture],
    }));


    const vehicleFormArray: FormArray = this._fb.array(vehicleFGs);
    ((this.myAccountForm as FormGroup).get('Owner') as FormGroup).setControl('Vehicles', vehicleFormArray);

我认为我遇到的问题是在这一行 ((this.myAccountForm as FormGroup).get('Owner') as FormGroup).setControl('Vehicles', vehicleFormArray);

我想我没有正确绑定控件,知道吗?

标签: angularangular-reactive-forms

解决方案


而不是使用.setControl(),使用.addControl()

this.form = this.formBuilder.group({
  owner: this.formBuilder.group({}),
});

const vehicleFormGroups: FormGroup[] = this.vehicles.map(v => {
  return this.formBuilder.group({
    model: [
      v.Model,
    ],
    registrationPlate: [
      v.RegistrationPlate,
    ],
    lastServiceData: [
      v.LastServiceDate,
    ],
    vin: [
      v.Vin,
    ],
    yearManufacture: [
      v.YearManufacture,
    ],
  });
});

const vehiclesFormArray: FormArray = new FormArray(vehicleFormGroups);

(this.form.get('owner') as FormGroup).addControl('vehicles', vehiclesFormArray);

推荐阅读