Moshe
Moshe

Reputation: 2684

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

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'?

Upvotes: 0

Views: 1358

Answers (2)

Moshe
Moshe

Reputation: 2684

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

Upvotes: 0

Christopher Moore
Christopher Moore

Reputation: 3099

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

Upvotes: 5

Related Questions