I have the following form
in Angular created with FormBuilder
:
constructor(private fb: FormBuilder) {
this.myForm = fb.group({
'name': ['', [Validators.required],
'surname': ['', [Validators.required],
'email': ['', [validateEmail]],
'address': fb.group({
'street': [''],
'housenumber': [''],
'postcode': ['']
}, { validator: fullAddressValidator })
});
}
Does exist a way to programmatically append new fields such as FormControl
or new FormGroup
to myForm
?
I mean if I want to add new fields on demand or on some conditions, how to add items to the same form that is created the first time in the constructor
?
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('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.
FormControl and FormGroup in AngularFormGroup is used with FormControl to track the value and validate the state of form control. In practice, FormGroup aggregates the values of each child FormControl into a single object, using each control name as the key.
You can use addControl
method of FormGroup class as per documentation
So you can do as below :
this.myForm.addControl('newcontrol',[]);
To add upon what @ranakrunal9 said.
If you would like to use validators with addControl do the following:
this.myForm.addControl('newControl', new FormControl('', Validators.required));
Just don't forget to add the following import
import {FormControl} from "@angular/forms";
Reference to addControl: https://angular.io/api/forms/FormGroup#addControl
Reference to FormControl: https://angular.io/api/forms/FormControl
In my opinion, you could just use an intermediate variable for this purpose. Take a look at the next example:
constructor(private fb: FormBuilder) {
let group = {
'name': ['', [Validators.required]],
'surname': ['', [Validators.required]],
'email': ['', [Validators.required]]
};
let middlename = true;
if(middlename) {
group['middlename'] = ['', [Validators.required]];
}
this.myForm = fb.group(group);
}
Also, it would a better idea to transfer a form initiation in ngOnInit hook, instead of component constructor.
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