Search code examples
angularangular-formsangular-formbuilder

best practice of adding a new property to a formGroup


What is the right way of adding a new object property to angular formGroup?

I have this set up:

ngOnInit() {
  this.form = this.fb.group({
    // store is the formGroupname
    store: this.fb.group({
      // branch and code are formControlName
      branch: ['asdf', Validators.required],
      code: ['asdf', Validators.required],
    }),
    selector: this.createStock({}),
    stock: this.fb.array([
      this.createStock({product_id: '1', quantity: 20}),
      this.createStock({product_id: '2', quantity: 30}),
      this.createStock({product_id: '3', quantity: 40}),
    ]),
  });
}

And inside the store property, I want to add if a checkbox is clicked. Upon reading on the angular documentation I have this solution that is working but giving me red line on vscode. I wonder is this the right way?

Solution:

onSubmitForm() {

  // adding dynamic formgroup
  if(this.form.get('checkBoxStore').value)
  this.form.get('store').addControl(
    'foo',
    this.fb.group({
      testingAdd: this.form.get('test').value,
    })
  );
}

Image:

enter image description here It's giving me an error message but working just fine. Weird but ok.


Solution

  • You are getting that error because FormGroup extends AbstractControl, when you are using get() it is a type of AbstractControl so to resolve this you need to cast it as a FormGroup

    (this.form.get('store') as FormGroup).addControl(...)
    

    See stackblitz