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

147
Vistas
Angular Toggle values in array changes position

I have an array with 4 values which I toggle (remove and Add to the array).

selectedSections: any[] = ['one', 'two', 'three', 'four'];

Then I have a button which I would click to make each selected appear and disappear.

<button (click)="toggleVal('one')">Toggle One</button>
<button (click)="toggleVal('two')">Toggle Two</button>
<button (click)="toggleVal('three')">Toggle Three</button>
<button (click)="toggleVal('four')">Toggle Four</button>

My issue is that the function below does the toggle job greatly but I need to be able to make the values appear back into the same position that they are now. At the moment everytime a value is added it's added to the end and I need to either be able to specify what position I want it added to or a way to make them stay in position.

Here is the code below:

toggleVal(val: any) {
    if (this.selectedSections.includes(val)) {
      let index = this.selectedSections.indexOf(val);
      this.selectedSections.splice(index, 1);
    } else {
      this.selectedSections.push(val);
    }
    this.howMany();
    this.filterData();
}

How can I get it to do this?

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

0

You can pass index value you want with your function in your html. Then you can use: arr.splice(index, 0, item);

It will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

about 4 years ago · Juan Pablo Isaza Denunciar

0

<button (click)="toggleVal('one', 1)">Toggle One</button>
<button (click)="toggleVal('two', 2)">Toggle Two</button>
<button (click)="toggleVal('three', 3)">Toggle Three</button>
<button (click)="toggleVal('four', 4)">Toggle Four</button>

toggleVal(val: any, i: number) {
if (this.selectedSections.includes(val)) {
  let index = this.selectedSections.indexOf(val);
  this.selectedSections.slice(index, 1);
} else {
  this.selectedSections.splice(i, 0, val);
}
this.howMany();
this.filterData();
}
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