candidateForm:FormGroup;
constructor(private fBuilder: FormBuilder){ }
ngOnInit(){
this.candidateForm = this.fBuilder.group({
fname: [null, [Validators.required]],
lname: [null, [Validators.required]],
address: this.fBuilder.group({
address1: [null],
address2: [null],
})
})
}
How to add a FormControl named address3
to the form group address
? And similarly how to remove them from the same FormGroup?
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!
This works for me:
(this.candidateForm.get('address') as FormGroup).addControl('address3', this.formBuilder.control(null));
(this.candidateForm.get('address') as FormGroup).removeControl('address3');