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

518 Views Asked by At

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.

2

There are 2 best solutions below

1
IDK4real On BEST ANSWER

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().

0
user11423673 On

You could place the buttons inside an *ngFor. For example if you want 5 buttons then

in your html template

<div class="btn-toolbar" *ngFor="let button of buttonArray; index as i">
    <button [id]="'button'+i" type="button" class="btn btn-primary" (click)="yourClickMethod()">Button {{i}}</button>
  
</div>

in your ts file

buttonArray = new Array(5);// here give the number as per the number of buttons your require