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
Since Angular 8 you can use this.formArray.clear()
to clear all values in form array.
It's a simpler and more efficient alternative to removing all elements one by one
Angular v4.4 if you need to save the same reference to the instance of FormArray try this:
purgeForm(form: FormArray) {
while (0 !== form.length) {
form.removeAt(0);
}
}
Update: Angular 8 finally got method to clear the Array FormArray.clear()
Use FormArray.clear() to remove all the elements of an array in a FormArray
I never tried using formArray, I have always worked with FormGroup, and you can remove all controls using:
Object.keys(this.formGroup.controls).forEach(key => {
this.formGroup.removeControl(key);
});
being formGroup an instance of FormGroup.
I had same problem. There are two ways to solve this issue.
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 withformArray.valueChanges
, will not be lost.
See the FormArray documentation for more information.
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.