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 ''.
First, we need to import the FormArray from the Angular Forms Module. Build a formGroup orderForm using the FormBuilder. We define items as FormArray. We need to capture two fields under each item, the name of the item & description and price.
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)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With