1
votes

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
You might take a look at: stackoverflow.com/questions/50520278/… in regards to .setControl() - Brandon
Can you write a answer? - Miomir Dancevic
Let me see what I can do - Brandon
You should be able to use .addControl() instead of .setControl() - Brandon

1 Answers

1
votes

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