Angular2 get clicked element id

前端 未结 9 1917
深忆病人
深忆病人 2020-11-29 20:07

I have such click event

 
 
相关标签:
9条回答
  • 2020-11-29 20:51

    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

    0 讨论(0)
  • 2020-11-29 20:52

    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?
    0 讨论(0)
  • 2020-11-29 20:55

    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); 
    }
    
    0 讨论(0)
提交回复
热议问题