Get button id

Hi guys,
I have an app with multiple buttons. Each of them has their own id like

<button ion-button color="light" id="button1" (click)="handleClick($event)">Button Text 1</button> <button ion-button color="light" id="button2" (click)="handleClick($event)">Button Text 2</button>

My question is that how can I pass the Id of each button to the handleClick method so can I handle them separately in js code.

Thank you in advance

Sharing click handlers for multiple buttons is not very idiomatic. Why can’t you just have two separate click handlers?

If the answer is "because I’m generating a bunch of them with ngFor", then what are you looping across?

Thank you very much for the reply. I’ve also thought about that.

However, I’m just curious, does that mean there’s no way for us to pass the id to the handler?

does that mean there’s no way for us to pass the id to the handler?

There is. The commands like event.srcElement are browser-specific, but there are ways to get it to work for any browser. You might want to search Stack Overflow answers. There are several code examples already.

The precise way you phrase that question, I would have to answer “no, I can’t think of one”. However, if we relax the way the question is worded to “is there any way I can get the id from the handler”, then yes, a couple at least.

The most natural way works if you are using ngFor, which is why I asked about that. You can derive both the id and a parameter to the click handler from a common source:

<template ngFor let-foo [ngForOf]="foos">
  <button ion-button (click)="onFrotz(foo)" [id]="foo.id">frotz {{foo.name}}</button>
</template>

The way you’ve written it (hardcoded with no ngFor) would probably require some rather fragile DOM kludgery, like:

handleClick(evt: MouseEvent) {
  let btnid = evt.target.parentElement.getAttribute("id");
}

Highly unrecommended, because it relies on implementation details of Ionic’s button component which could change out from under us at any time.

I understand. Thanks guys for all the reply.