Angular2 get clicked element id

Angular

Angular Problem Overview


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

Angular Solutions


Solution 1 - Angular

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:

Solution 2 - Angular

For TypeScript users:

    toggle(event: Event): void {
        let elementId: string = (event.target as Element).id;
        // do something with the id... 
    }

Solution 3 - Angular

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

Solution 4 - Angular

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

Solution 5 - Angular

There is no need to pass the entire event (unless you need other aspects of the event than you have stated). In fact, it is not recommended. You can pass the element reference with just a little modification.

import {Component} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
    <button #btn1 (click)="toggle(btn1)" class="someclass" id="btn1">Button 1</button>
    <button #btn2 (click)="toggle(btn2)" class="someclass" id="btn2">Button 2</button>
  `
})
export class AppComponent {
  buttonValue: string;

  toggle(button) {
    this.buttonValue = button.id;
  }

}

StackBlitz demo

Technically, you don't need to find the button that was clicked, because you have passed the actual element.

Angular guidance

Solution 6 - Angular

When your HTMLElement doesn't have an id, name or class to call,

then use

<input type="text" (click)="selectedInput($event)">

selectedInput(event: MouseEvent) {
   log(event.srcElement) // HTMInputLElement
}

Solution 7 - Angular

You can use its interface HTMLButtonElement that inherits from its parent HTMLElement !

This way you will be able to have auto-completion...

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

toggle(event: MouseEvent) {
    const button = event.target as HTMLButtonElement;
    console.log(button.id);
    console.log(button.className);
 }

To see all list of HTMLElement from the World Wide Web Consortium (W3C) documentation

StackBlitz demo

Solution 8 - Angular

do like this simply: (as said in comment here is with example with two methods)

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app', 
    template: `
      <button (click)="checkEvent($event,'a')" id="abc" class="def">Display Toastr</button>
      <button (click)="checkEvent($event,'b')" id="abc1" class="def1">Display Toastr1</button>
    `
})
export class AppComponent {
  checkEvent(event, id){
    console.log(event, id, event.srcElement.attributes.id);
  }
}

demo: http://plnkr.co/edit/5kJaj9D13srJxmod213r?p=preview

Solution 9 - Angular

For nested html, use closest

<button (click)="toggle($event)" class="someclass" id="btn1">
    <i class="fa fa-user"></i>
</button>

toggle(event) {
   (event.target.closest('button') as Element).id; 
}

Solution 10 - Angular

If you want to have access to the id attribute of the button in angular 6 follow this code

`@Component({
  selector: 'my-app',
  template: `
    <button (click)="clicked($event)" id="myId">Click Me</button>
  `
})
export class AppComponent {
  clicked(event) {
    const target = event.target || event.srcElement || event.currentTarget;
    const idAttr = target.attributes.id;
    const value = idAttr.nodeValue;
  }
}`

your id in the value,

the value of value is myId.

Solution 11 - Angular

You can retrieve the value of an attribute by its name, enabling you to get the value of a custom attribute such as an attribute from a Directive:

<button (click)="toggle($event)" id="btn1" myCustomAttribute="somevalue"></button>


toggle( event: Event ) {
  const eventTarget: Element = event.target as Element;
  const elementId: string = eventTarget.id;
  const attribVal: string = eventTarget.attributes['myCustomAttribute'].nodeValue;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsreginogemohView Question on Stackoverflow
Solution 1 - AngularThierry TemplierView Answer on Stackoverflow
Solution 2 - AngularquidkidView Answer on Stackoverflow
Solution 3 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 4 - AngularmicronyksView Answer on Stackoverflow
Solution 5 - AngularGregView Answer on Stackoverflow
Solution 6 - AngularWasiFView Answer on Stackoverflow
Solution 7 - AngularA. MorelView Answer on Stackoverflow
Solution 8 - AngularPardeep JainView Answer on Stackoverflow
Solution 9 - AngularKurt Van den BrandenView Answer on Stackoverflow
Solution 10 - AngularEhsanView Answer on Stackoverflow
Solution 11 - AngularStackOverflowUserView Answer on Stackoverflow