Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addControl to FormGroup dynamically in Angular

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 ''.

like image 766
joeSmith Avatar asked Nov 30 '17 12:11

joeSmith


People also ask

How do I declare FormArray in FormGroup?

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.


2 Answers

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.

like image 89
Siro Avatar answered Sep 28 '22 22:09

Siro


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)); } 
like image 32
AT82 Avatar answered Sep 29 '22 00:09

AT82