0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks.. This is working but how can I deselect selected one button. Can you please help me
Want to select one button at time but both can be deselected
I have updated it to deselect the button if you click on it when it has already been selected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.