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?
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; }
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With