【问题标题】:Reactive forms angular adding new controls反应形式角度添加新控件
【发布时间】:2018-10-12 04:12:39
【问题描述】:

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

这就是我现在所拥有的

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

我认为我没有正确绑定控件,有什么想法吗?

【问题讨论】:

标签: angular angular-reactive-forms


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
相关资源
最近更新 更多