Home > Net >  Angular toggle item in array always removing first value from array and ignoring given value
Angular toggle item in array always removing first value from array and ignoring given value

Time:07-05

I am trying to get a button click toggle a given value from an array.

So here is the array with all the values:

values = ['one', 'two', 'three', 'four'];

Here I execute the toggleTest method and pass string value of 'one'

<button (click)="toggleTest('one')"></button>

Finally here is should remove or add the value from the values array, depending if it exists or not.

toggleTest(value) {
   // if value exists in this.values then remove it ... else add it.
   So I tried this:

   if (this.values.includes(value)) {
      // it's there so lets remove it
      this.values.splice(value, 1);
   } else {
     // its not there so lets add it
     this.values.push(value, 1);
   }

}

When I try this it removes the first entry all the time and ignores the value given...it just removes one from the values array.

How can I fix this?

CodePudding user response:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().

The push() method adds one or more elements to the end of an array and returns the new length of the array.

toggleTest(val){

   if (this.values.includes(val)) {
      // it's there so lets remove it
     let index = this.values.indexOf(val);
     this.values.splice(index, 1);
   } else {
     // its not there so lets add it
     this.values.push(val);
   }
}

CodePudding user response:

The splice function takes an index as its first parameter, not the value itself (see here).

So you could replace this:

this.values.splice(value, 1);

with this:

let index = this.values.indexOf(value);
this.values.splice(index, 1);
  • Related