angular 2 remove all items from a formarray

Karl O'Connor picture Karl O'Connor · Jan 25, 2017 · Viewed 107.3k times · Source

I have a form array inside a formbuilder and i am dynamically changing forms, i.e. on click load data from application 1 etc.

The issue i am having is that all the data loads in but the data in the formarray stays and just concats the old items with new.

How do I clear that formarray to only have the new items.

I've tried this

const control2 = <FormArray>this.registerForm.controls['other_Partners'];
        control2.setValue([]);

but it doesn't work.

Any ideas? thanks

in nginit

ngonitit is not being called on click

Answer

CamelD picture CamelD · Jan 25, 2017

I had same problem. There are two ways to solve this issue.

Preserve subscription

You can manually clear each FormArray element by calling the removeAt(i) function in a loop.

clearFormArray = (formArray: FormArray) => {
  while (formArray.length !== 0) {
    formArray.removeAt(0)
  }
}

The advantage to this approach is that any subscriptions on your formArray, such as that registered with formArray.valueChanges, will not be lost.

See the FormArray documentation for more information.


Cleaner method (but breaks subscription references)

You can replace whole FormArray with a new one.

clearFormArray = (formArray: FormArray) => {
  formArray = this.formBuilder.array([]);
}

This approach causes an issue if you're subscribed to the formArray.valueChanges observable! If you replace the FromArray with a new array, you will lose the reference to the observable that you're subscribed to.