Angular2 get clicked element id

I have such click event

 <button (click)="toggle($event)" class="someclass" id="btn1"></button>
 <button (click)="toggle($event)" class="someclass" id="btn2"></button>

I am catching the event in my function input param and want to find out what exactly button was clicked.

toggle(event) {

}

but event does not have an id property.

altKey: false
bubbles: true
button: 0
buttons: 0
cancelBubble: false
cancelable: true
clientX: 1198
clientY: 29
ctrlKey: false
currentTarget: button#hdrbtn_notificaton.mdl-button.mdl-js-button.mdl-js-ripple-effect.mdl-button--icon
defaultPrevented: false
detail: 1
eventPhase: 3
fromElement: null
isTrusted: true
isTrusted: true
layerX: -566
layerY: 5
metaKey: false
movementX: 0
movementY: 0
offsetX: 22
offsetY: 13
pageX: 1198
pageY: 29
path: Array[13]
relatedTarget: null
returnValue: true
screenX: 1797
screenY: 148
shiftKey: false
sourceCapabilities: InputDeviceCapabilities
srcElement: span.mdl-button__ripple-container
target: span.mdl-button__ripple-container
timeStamp: 1458032708743
toElement: span.mdl-button__ripple-container
type: "click"
view: Window
webkitMovementX: 0
webkitMovementY: 0
which: 1
x: 1198
y: 29

How can I find an id?

UPDATE: Plunkers are all good but in my case I have locally:

event.srcElement.attributes.id - undefined event.currentTarget.id - has the value

I am using chrome latest Version 49.0.2623.87 m

Could it be Material Design Lite thing? because I am using it.

enter image description here


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?

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); 
}