Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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'

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar

0

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);
   }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda