Search code examples
angularevent-binding

How to set event binding for group of buttons in Angular?


Is there a way to bind the same event to multiple buttons or a button group?(instead of binding them individually) For example considering just two buttons,

<div class="btn-toolbar">
    <button type="button" class="btn btn-primary">Button 1</button>
    <button type="button" class="btn btn-primary">Button 2</button>
</div>

I want to bind a click event to both of these buttons so that when either of the buttons are clicked, the same function is called.


Solution

  • Each html element as its own listeners.

    As such, you need to bind each element individually as such:

    <div class="btn-toolbar">
        <button type="button" class="btn btn-primary" (click)="methodOne()">Button 1</button>
        <button type="button" class="btn btn-primary" (click)="methodOne()">Button 2</button>
    </div>
    

    You could try to bypass this by creating a container for the elements that you want to bind, and add the binding there, like so:

    <div class="btn-toolbar">
        <div (click)="methodOne()">
            <button type="button" class="btn btn-primary">Button 1</button>
            <button type="button" class="btn btn-primary">Button 2</button>
        </div>
    </div>
    

    The problem with this approach is that any empty space between both buttons would also trigger the methodOne().