Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set active class on list of buttons

Tags:

angular

I have an Angular 2 app that has a component that contains a list of filter buttons. One of them can be active at any one time. The button definitions come from some json and will one day be sent from the server.

My problem is how to set a style on the currently clicked button. Should I set it in the click event handler? So how do I know which button was clicked?

My Component looks like this :

import { Component, EventEmitter, Output }  from '@angular/core';

@Component({
    selector: 'tileFilter',
    template: require('./tileFilter.component.html'),
    styles: [require('.//tileFilter.component.scss').toString()]
})

export class TileFilterComponent {

@Output() onCategorySelected = new EventEmitter<number>();

public activeClass: string = "nonactive"

 private categories: any[] = [
    { "Id": 0, "Name": "All" },
    { "Id": 3, "Name": "Popup" },
    { "Id": 4, "Name": "Cafe" },
    { "Id": 5, "Name": "Pub or bar" },
    { "Id": 9, "Name": "Restaurant" }
];

    constructor() {}

    onClick(category:any){
        this.activeClass ="active";
        this.onCategorySelected.emit(<number>category.Id);
    }

}

And my HTML looks like this :

<ul class="tile-filters inline-list inline-list--sm unstyled-list collapse">
  <li *ngFor="let c of categories">
      <button class="button button--recede button--sm {{activeClass}}" (click)="onClick(c)">{{c.Name}}</button>
  </li>
</ul>

What's the common pattern for this?

like image 958
Ben Cameron Avatar asked Jul 26 '16 15:07

Ben Cameron


2 Answers

The common pattern is to create a new variable to keep track of which button is clicked, to reassign that variable on a click event, and to bind the active class on whether or not the current button equals the selected button.

From the Angular 2 tutorial:

//...

<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

//...

export class AppComponent {
  title = 'Tour of Heroes';
  heroes = HEROES;
  selectedHero: Hero;
  onSelect(hero: Hero) { this.selectedHero = hero; }
}
like image 94
Pace Avatar answered Oct 16 '22 22:10

Pace


You can achieve this by only modifying your html code and more over it is angular 2 standard as well.

    <li *ngFor=" let c of categories ">
          <button [class.active]="clicked === c" 
             (click)="clicked = (clicked === c ? null :c)">{{c.Name}}</button>
    </li>

More Info

like image 40
Prashobh Avatar answered Oct 16 '22 23:10

Prashobh