How can I add a FormControl to a FormGroup dynamically in Angular?
For example, I would like to add a mandatory control which name is "new" and its default value is ''.
addControl
is what you need. Please note the second parameters must be a FormControl instance like so:
this.testForm.addControl('new', new FormControl('', Validators.required));
You can also add the validators dynamically if you want with the setValidators
method. Calling this overwrites any existing sync validators.