3

I have a ControlArray and at some point I need to remove multiple items from it , or easier , just clear/empty the whole array.

This is the current array :

       let myControls = new ControlArray([]);
       // Add some items to this array : 

          for(let i = 0 ; i<5 ; i++){
                myControls.push({
                    firstName : new Control( '' , Validators.required ) ,
                    lastName  : new Control( '' , Validators.required ) ,
                })
           }

       // After this my controlArray has 5 controls and 
       //everything works in the view properly .

Now I have a button that has a (click) event bind to it and I want to clear ( remove all the controls ) from myControls , but I can't find the solution.

In the documentations , there is a myControl.removeAt(index) function which removes only one item , but there is not any function that removes all the items.

Also , I've tried this :

          for(let i = 0 ; i<myControls.length ; i++){
                myControls.removeAt(i);
           }

But obviously this wont work because every time you remove an item from the array , the index will change !!!

Thanks in advance.

1
  • The ControlArray seems to have a public controls: AbstractControl[] property. Looking at the code, the ControlArray-specific methods are using this array directly. I suppose then it is legal and endorsed to do myControls.controls = [] or myControls.controls.length = 0. Apr 25, 2016 at 12:25

2 Answers 2

10

not much related angular, but normally when you are splicing an array in a loop you want to go backward with your counter, so that the next index i-- would still refer to the original element in the array

for(var i=myControls.length;i-->0;){
    myControls.removeAt(i);
}
5

I haven't checked if there is a better solution but this should work as well:

while(myControl.length) {
  myControls.removeAt(0);
}
5
  • Looks extremely hacky though .:) , I wish Angular team would have thought about this.
    – user4328424
    Apr 25, 2016 at 12:17
  • You can try one of those stackoverflow.com/questions/1232040/… I don't actively use JS or TS myself (only Dart) Apr 25, 2016 at 12:18
  • 2
    actually none of them is related to this , because all of those are touching the array itself , but in here , myControl is not an array and has a special function called removeAt() . The array is living inside in controls. But again , so far your answer is the best way unless Angular team adds a removeAll() function to that element. Thanks again.
    – user4328424
    Apr 26, 2016 at 3:58
  • You are right github.com/angular/angular/blob/… Apr 26, 2016 at 4:40
  • 1
    Most elegant and efficient way I've found, Gunter you're my saver once again :D
    – KCarnaille
    Jun 2, 2017 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy