简体   繁体   中英

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.

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 .

使用removeAt()方法从formarray中删除元素

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM