Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove the FormArray in angular2 reactive forms

Tags:

angular

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.

like image 929
Muhammad Irfan Mayo Avatar asked Sep 13 '17 09:09

Muhammad Irfan Mayo


2 Answers

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.

like image 56
Pengyy Avatar answered Sep 20 '22 11:09

Pengyy


use removeAt() method for removing the element from formarray

like image 24
Abdul Hameed Avatar answered Sep 22 '22 11:09

Abdul Hameed