Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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?

>Solution :

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);
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading