Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple controls from ControlArray

Tags:

angular

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.


2 Answers

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);
}
like image 175
undefinederror Avatar answered Apr 10 '26 17:04

undefinederror


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

while(myControl.length) {
  myControls.removeAt(0);
}
like image 38
Günter Zöchbauer Avatar answered Apr 10 '26 17:04

Günter Zöchbauer