简体   繁体   English

如何删除angular2反应形式的FormArray

[英]how to remove the FormArray in angular2 reactive forms

I'm having issue on removing the FormArray from ReactiveForm. 我在从ReactiveForm中删除FormArray时遇到了问题。

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 现在我要删除formControl surveyName

this.survey.removeControl('surveyName');

And above code is working fine for surveyName. 以上代码适用于surveyName。 But what thing i can use for deletion the form array sections. 但是我可以使用什么来删除表单数组部分。 I want to delete the whole section object with key. 我想用键删除整个section对象。

You should always use removeControl to remove both formControl and entire formArray from reactiveform. 您应该始终使用removeControl从reactiveform中删除formControl和整个 formArray。

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. 你需要注意的事情是你应该使用ngIf控制在从被动ngIf中移除后不显示被移除的元素。

see sample demo . 看示例演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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