Search code examples
javascriptangularangular2-templateangular2-databinding

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


Solution

  • 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