如何清除 Angular 响应式表单中的 FormArray

How do I clear the FormArray in Angular Reactive Forms

我正在重置表格。它重置整个表单,但 FormArray 除外。

创建表单并在其中声明 formArray

createForm(){
    this.invoiceForm = this.formBuilder.group({
      'name': ['', Validators.required],
      'gst': [''],
      'currency': [''],
      'addressLine1': ['', Validators.required],
      'addressLine2': [''],
      'city': ['', Validators.required],
      'state': ['', Validators.required],
      'country': ['', Validators.required],
      'postalCode': ['', Validators.required],
      'email': ['', [Validators.required, Validators.email]],
      'invoiceparticulars': this.formBuilder.array([]),
      'isGstshidden' : true
    });

  }

尝试通过重置数据来修改传入数据的表单详细信息,即使我调用了 reset() 函数 formArray 并保留了其中的先前条目。

 modifyInvoice(index){

   this.invoiceForm.reset();

   let modifyData = this.modifyInvoiceArray[index];
   console.log(modifyData);

   this.invoiceNumber = modifyData.invoiceNumber;
   this.invoiceForm.patchValue({name: modifyData.address.Name});
   this.invoiceForm.patchValue({email: modifyData.email});
   this.invoiceForm.patchValue({gst: modifyData.GSTnumber});
   this.invoiceForm.patchValue({addressLine1: modifyData.address.AddressLine1});
   this.invoiceForm.patchValue({addressLine2: modifyData.address.AddressLine2});
   this.invoiceForm.patchValue({city: modifyData.address.City});
   this.invoiceForm.patchValue({country: modifyData.address.Country});
   this.invoiceForm.patchValue({postalCode: modifyData.address.PostalCode});
   this.invoiceForm.patchValue({state: modifyData.address.State});
   console.log(modifyData['particulars']);
}

Try to add this code

const control = <FormArray>this.invoiceForm.controls['invoiceparticulars'];
        for(let i = control.length-1; i >= 0; i--) {
            control.removeAt(i)
    }

Angular 8

只需在 formArrays 上使用 clear() 方法:

(this.invoiceForm.controls['invoiceparticulars']).clear();

或:

let frmArray = this.invoiceForm.get('invoiceparticulars') as FormArray;
frmArray.clear();