Angular2 dynamic buttons where only one can be selected at a time

1.3k Views Asked by At

I am trying to create the following UI/UX buttons:
.. [2015] [2016] [2017]

Where the current year (in the time of writing, 2017) is 'selected' by default, however, when the user clicks '2015', '2017' and '2016' should be deselected (These buttons are 'mutually exclusive')

The buttons are being generated from an external data source that provides me data with years:

<button *ngFor="let year of styles.years"  type="button" name="button" class="btn btn-default" id="{{year.year}}">
  {{year.year}}
</button>

How can I create a system of buttons where one button is 'auto-selected', and when 'other' button is selected, it deselects the button that's actively selected, and sets the now clicked button to 'selected'?

2

There are 2 best solutions below

3
On BEST ANSWER

Set a property in the component activeYear and control it by binding logic to the (click) of a button

<button *ngFor="let year of styles.years"  
    [ngClass]="{ active: activeYear === year }"
    (click)="activeYear = year.year"
    type="button" name="button" class="btn btn-default"  id="{{year.year}}">
    {{year.year}}
</button>

Heres a working Plunker demonstrating this

0
On

For those who would like to use multiple classes, like in my case: Add a comma, and add a new style:condition.

[ngClass]="{ selected: activeYear === year.year, 'btn-default': activeYear !== year.year}"

Hope this helps others as well