addControl to FormGroup dynamically in Angular
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.
If you are using FormBuilder
for your form, you can also use that for adding a control:
constructor(private fb: FormBuilder) { } method() { this.testForm.addControl('new', this.fb.control('', Validators.required));}
simple use:
this.testForm.addControl('new', this.fb.group({ name: ['', Validators.required] }));