Angular2 get clicked element id
If you want to have access to the id
attribute of the button you can leverage the srcElement
property of the event:
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<button (click)="onClick($event)" id="test">Click</button>
`
})
export class AppComponent {
onClick(event) {
var target = event.target || event.srcElement || event.currentTarget;
var idAttr = target.attributes.id;
var value = idAttr.nodeValue;
}
}
See this plunkr: https://plnkr.co/edit/QGdou4?p=preview.
See this question:
- How can I make event.srcElement work in Firefox and what does it mean?
You could just pass a static value (or a variable from *ngFor
or whatever)
<button (click)="toggle(1)" class="someclass">
<button (click)="toggle(2)" class="someclass">
For TypeScript users:
toggle(event: Event): void {
let elementId: string = (event.target as Element).id;
// do something with the id...
}
Finally found the simplest way:
<button (click)="toggle($event)" class="someclass" id="btn1"></button>
<button (click)="toggle($event)" class="someclass" id="btn2"></button>
toggle(event) {
console.log(event.target.id);
}