Search code examples
htmlbuttonangular5angular2-formsangular4-forms

Toggle class between two buttons in Angular2


I am using angular 2 and I have two buttons I want toggle class between two buttons but. Below is my code

<button class="btn rounded" [ngClass]="{'btn-default': !clicked, 'btn-primary': clicked}" (click)="clicked = !clicked">
                                    <i class="fa fa-long-arrow-up"></i>
                                </button>
                                <button class="btn rounded" [ngClass]="{'btn-default': !clicked, 'btn-primary': clicked}" (click)="clicked = !clicked">
                                    <i class="fa fa-long-arrow-down"></i>
                                </button>

My problem is I want to toggle class but at time only one button can select and other condition is both buttons can be deselect. On click of one button other button should be deselect and once you click on selected button that button should be deselect and I want to do this only using buttons. Please help


Solution

  • You can use this pattern which will work for any number of buttons:

    In your controller, set up an array of buttons and a selectedButton variable

    buttons= [
      {class: "fa fa-long-arrow-up", name: "button1"},
      {class: "fa fa-long-arrow-down", name: "button2"},
    ]
    selectedButton;
    toggleSelect(button) {
        if (button == this.selectedButton) {
            this.selectedButton = undefined
        } else {
            this.selectedButton = button
        }
    }
    

    Then in your template populate the selectedButton on click, and set your class based on whether it is selected

    <button *ngFor="let button of buttons" class="btn rounded" [ngClass]="(selectedButton == button) ? 'btn-primary' : 'btn-default'" (click)="toggleSelect(button)">
        <i [class]="button.class"></i>
    </button>
    

    This way you could have any number of buttons and only one will ever be "selected" at a time

    working example: https://stackblitz.com/edit/angular-v9zlaz?file=src%2Fapp%2Fapp.component.html