Dynamically addControl to formgroup Angular 5

joeSmith picture joeSmith · Nov 30, 2017 · Viewed 85.1k times · Source

Trying to dynamically add a new formControl entry to my formGroup in Angular.

method() {
  this.testForm.addControl('new', ('', Validators.required));
}

Can this be done?

Answer

Siro picture Siro · Nov 30, 2017

Sure, but the second parameters should be a FormControl instance. Something like:

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

You can also add the validators dynamically if you want with the setValidators method.

More information here: https://angular.io/api/forms/FormGroup#addControl