反应性表格有角度地添加了新控件

时间:2018-10-11 19:23:11

标签: angular angular-reactive-forms

我试图在数组的表单上添加新的表单控件,但是我有一个问题,就是即使数组中有一些值,我也总是空控件

这就是我现在拥有的

 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);

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

1 个答案:

答案 0 :(得分:0)

使用.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);