Muhammad Irfan Mayo
Muhammad Irfan Mayo

Reputation: 143

how to remove the FormArray in angular2 reactive forms

I'm having issue on removing the FormArray from ReactiveForm.

I have the following code :

ngOnInit() {
  this.survey = new FormGroup({
    surveyName: new FormControl(''),
    sections: new FormArray([
      this.initSection(), 
    ]), 
  });      
}

initSection(){
  return new FormGroup({
    sectionTitle : new FormControl(''),
    sectionDescription : new FormControl(''),
  });
}

addSection(){
  const control = <FormArray>this.survey.controls['sections'];
  control.push(this.initSection());
}

Now for deletion the formControl surveyName I just do

this.survey.removeControl('surveyName');

And above code is working fine for surveyName. But what thing i can use for deletion the form array sections. I want to delete the whole section object with key.

Upvotes: 6

Views: 11348

Answers (2)

Abdul Hameed
Abdul Hameed

Reputation: 103

use removeAt() method for removing the element from formarray

Upvotes: 3

Pengyy
Pengyy

Reputation: 38199

You should always use removeControl to remove both formControl and entire formArray from reactiveform.

Things you have to pay attention is that you should use ngIf to control not showing the removed element after it's removed from reactiveform.

see sample demo.

Upvotes: 6

Related Questions