How to Append New Formgroup or Formcontrol to Form

I have the following form in Angular created with FormBuilder:

constructor(private fb: FormBuilder) {
  this.myForm = fb.group({
      'name': ['', [Validators.required],
      'surname': ['', [Validators.required],
      'email': ['', [validateEmail]],
      'address': fb.group({
          'street': [''],
          'housenumber': [''],
          'postcode': ['']
      }, { validator: fullAddressValidator })
  });
}

Does exist a way to programmatically append new fields such as FormControl or new FormGroup to myForm ?

I mean if I want to add new fields on demand or on some conditions, how to add items to the same form that is created the first time in the constructor?

1

4 Answers

You can use addControl method of FormGroup class as per documentation

So you can do as below :

this.myForm.addControl('newcontrol',[]);
5

To add upon what @ranakrunal9 said.

If you would like to use validators with addControl do the following:

this.myForm.addControl('newControl', new FormControl('', Validators.required));

Just don't forget to add the following import

import {FormControl} from "@angular/forms";

Reference to addControl:

Reference to FormControl:

0

In my opinion, you could just use an intermediate variable for this purpose. Take a look at the next example:

  constructor(private fb: FormBuilder) {
    let group = {
      'name': ['', [Validators.required]],
      'surname': ['', [Validators.required]],
      'email': ['', [Validators.required]]
    };

    let middlename = true;

    if(middlename) {
      group['middlename'] = ['', [Validators.required]];
    }

      this.myForm = fb.group(group);
    }

Also, it would a better idea to transfer a form initiation in ngOnInit hook, instead of component constructor.

3

I had the same issue, but since I already have a empty FormGroup {} inside the main FormGroup I was able to append FormControls like this:

(this.myForm.get("form_group_name") as FormGroup).addControl("item1", new FormControl("default val"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest