Sergino
Sergino

Reputation: 10808

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

Upvotes: 101

Views: 308233

Answers (13)

Sherif eldeeb
Sherif eldeeb

Reputation: 2186

all the answeres here leads to an issue, the $event here not always refers to the button itself, and may refer to another element

here is an example

<button (click)="onClick($event)">
  <mat-icon>ok</mat-icon>
  <span>Click here!</span>
</button>

and...

onClick(ev: MouseEvent){
  let target = ev.target
}

ev.target here can point to the icon or the <span elements rather that the button itself

one solution here is to check if the target is not a button, so your desired target here is ev.taget.parentElement instead of ev.target

Upvotes: 0

shyam yadav
shyam yadav

Reputation: 275

You can also use event.path like below

Html:

<tbody>
    <tr *ngFor="let r of rows" id="{{r}}">
        <td>
            <span>
                <button (click)="deleteRow($event)" type="button" 
                class="btn-close"></button> 
            </span>   
        </td>
     </tr>
 </tbody>

ts:

deleteRow(evemt:any){

this.rows.pop()
console.log(evemt.path[3].id);
}

in evemt.path[3].id 3 is which parent's you want to access start from 1 is immediate parent

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202138

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:

Upvotes: 171

StackOverflowUser
StackOverflowUser

Reputation: 1123

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

Upvotes: 1

Kurt Van den Branden
Kurt Van den Branden

Reputation: 12934

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

Upvotes: 2

WasiF
WasiF

Reputation: 28847

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
}

Upvotes: 4

A. Morel
A. Morel

Reputation: 10344

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

Upvotes: 3

Greg
Greg

Reputation: 776

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

Upvotes: 13

Ehsan
Ehsan

Reputation: 308

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.

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657058

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

Upvotes: 20

quidkid
quidkid

Reputation: 638

For TypeScript users:

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

Upvotes: 50

micronyks
micronyks

Reputation: 55443

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

Upvotes: 21

Pardeep Jain
Pardeep Jain

Reputation: 86720

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

Upvotes: 2

Related Questions