angular 2 remove all items from a formarray

后端 未结 15 1661
清歌不尽
清歌不尽 2020-12-07 15:30

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

相关标签:
15条回答
  • 2020-12-07 16:22

    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

    0 讨论(0)
  • 2020-12-07 16:25

    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);
      }
    }
    
    0 讨论(0)
  • 2020-12-07 16:25

    Update: Angular 8 finally got method to clear the Array FormArray.clear()

    0 讨论(0)
  • 2020-12-07 16:27

    Use FormArray.clear() to remove all the elements of an array in a FormArray

    0 讨论(0)
  • 2020-12-07 16:28

    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.

    0 讨论(0)
  • 2020-12-07 16:30

    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.

    0 讨论(0)
提交回复
热议问题