0

How can I change the style of each button once I click on it? enter image description here

I have several buttons and I need to achieve something similar to an active state, but in reality what you execute is a function.

I tried the following but I do not achieve an active state [ngClass]=" { 'btn-primary':categoria.nombre }

component.ts

ngOnInit() {
  this.eventos = this.fs.getEventosAll();
  this.categorias = this.fs.getCategorias();
}

filtrarEventos(categoria) {
 this.eventos = this.fs.filterEventos(categoria);
}

component.html

<button class="btn btn-sm" *ngFor="let categoria of categorias | async" (click)="filtrarEventos(categoria.nombre)" [ngClass]=" { 'btn-primary':categoria.nombre } ">
 {{ categoria.nombre }}
</button>
1
  • Make an array of object in which each object has a state, then use this state to trigger your UI interactions. Also, use English in your code (at least when sharing on SO) Commented Apr 6, 2019 at 16:53

2 Answers 2

3

You can first, add a property, let's say, categoriaActiva to the component holding the buttons, add

this.categoriaActiva = categoria

to the filtrarEventos callback, and finally add

[class.btn-primary]="categoria.nombre === categoriaActiva"

to the button.

Sign up to request clarification or add additional context in comments.

Comments

2

Here is the stackblitz of what you are trying to do

I called one method which sets the value of the clicked index

Template

   <div *ngFor="let categoria of categorias; let i = index" 
           (click)="changeState(i)" 
           [ngClass]="clickedIndex === i  ? 'primary' : 'secondary'">
       {{categoria.nombre}}
   </div>

Component

 changeState(index) {
    this.clickedIndex = index;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.