Angular2 get clicked element id

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

I have such click event

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

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

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

    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

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

    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.

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

    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

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

    For TypeScript users:

        toggle(event: Event): void {
            let elementId: string = (event.target as Element).id;
            // do something with the id... 
        }
    
    0 讨论(0)
提交回复
热议问题