Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add/remove FormControl from a nested FormGroup

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?

like image 250
Apar Adhikari Avatar asked Mar 15 '18 06:03

Apar Adhikari


3 Answers

This works for me:

(this.candidateForm.get('address') as FormGroup).addControl('address3', this.formBuilder.control(null));
(this.candidateForm.get('address') as FormGroup).removeControl('address3');
like image 115
Ricardo Luiz Ribeiro Avatar answered Oct 25 '22 10:10

Ricardo Luiz Ribeiro


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');
like image 44
Erex Avatar answered Oct 25 '22 09:10

Erex


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!

like image 22
Ali Adravi Avatar answered Oct 25 '22 09:10

Ali Adravi