Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear the FormArray in Angular Reactive Forms

I am doing resetting of form. It resets the whole form but except FormArray.

Creating the form and declaring formArray within it

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
    });

  }

Trying to modify details of the form from the incoming data by resetting the data even though I called reset() function formArray retaining previous entries in it.

 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']);
}
like image 409
Dhaanappagouda Patil Avatar asked May 03 '18 10:05

Dhaanappagouda Patil


People also ask

How do you clear FormArray controls?

How do I clear all values in FormArray? You can manually clear each FormArray element by calling the removeAt(i) function in a loop. The advantage to this approach is that any subscriptions on your formArray , such as that registered with formArray. valueChanges , will not be lost.

What does FormArray Clear () do?

clear()linkRemove all controls in the FormArray .

How do I disable FormControl in FormArray?

To disable the FormControls of a FormArray, "reset" makes it easy. Save this answer. Show activity on this post. (<FormArray>this.


1 Answers

Angular 8

simply use clear() method on formArrays :

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

OR :

let frmArray = this.invoiceForm.get('invoiceparticulars') as FormArray;
frmArray.clear();
like image 186
MajiD Avatar answered Sep 19 '22 23:09

MajiD