Reactive forms angular adding new controls

I am trying to add new form controls on form from array, but i have problem that i have always empty control, even if i have some values in array

This is what i have for now

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

The problem i think i have is in this line ((this.myAccountForm as FormGroup).get('Owner') as FormGroup).setControl('Vehicles', vehicleFormArray);

I think i dont bind controls properly, any idea?

1 answer

  • answered 2018-10-11 20:12 Brandon

    Instead of using .setControl(), use .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);