Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

angular - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...