1

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?

4
  • You might take a look at: stackoverflow.com/questions/50520278/… in regards to .setControl() Commented Oct 11, 2018 at 19:36
  • Can you write a answer? Commented Oct 11, 2018 at 19:40
  • Let me see what I can do Commented Oct 11, 2018 at 19:43
  • You should be able to use .addControl() instead of .setControl() Commented Oct 11, 2018 at 20:11

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I'll try to get a Stack Blitz going as an example. This code is working for me in my local dev environment.
You can view the console output at: stackblitz.com/edit/angular-form-array-example2 to see a working example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.