Search code examples
javascriptangular2-forms

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?


Solution

  • 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');