How to add/remove FormControl from a nested FormGroup
This works for me:
(this.candidateForm.get('address') as FormGroup).addControl('address3', this.formBuilder.control(null));
(this.candidateForm.get('address') as FormGroup).removeControl('address3');
First you have to get the sub FormGroup from your main FormGroup, and then you could use the addControl and removeControl refrenced in the documentation here: https://angular.io/api/forms/FormGroup.
So in your case it would be:
//Add:
this.candidateForm.get('address').addControl('address3',[]);
//Remove:
this.candidateForm.get('address').removeControl('address2');
I tried Adhikari answer but could not worked for me, it always throw error:
error TS2339: Property 'addControl' does not exist on type 'AbstractControl'.
His answer helped me to think, and finally I came out with this:
Write a getter property anywhere like this (to get the group):
get addressGroup() { return this.candidateForm.get('address'); }
Now wherever you want to add some controls, use like this:
if(this.addressGroup instanceof FormGroup){
var ctrl:AbstractControl = this.fBuilder.control('', [Validators.required]);
(<FormGroup>this.addressGroup).addControl('address3', ctrl);
var emailCtrl:AbstractControl = this.fBuilder.control('', [Validators.email]);
(<FormGroup>this.addressGroup).addControl('myEmail', emailCtrl);
var add4:AbstractControl = this.fBuilder.control('', []);
(<FormGroup>this.addressGroup).addControl('address4', add4);
}
It is an old question, but hope this will help someone!