Angular2, HostListener, how can I target an element? can I target based on class?

后端 未结 8 1142
后悔当初
后悔当初 2020-12-05 01:50

In Angular2, how can I target an element within the HostListener decorator?

@HostListener(\'dragstart\', [\'$event\'])
    onDragStart(ev:Event) {
        co         


        
相关标签:
8条回答
  • 2020-12-05 02:51

    I think better way for global listener is @hostliterner but if you want to target some element you can do like this

    <div (event)="onEvent($e)"></div>
    

    in your angular component

    onEvent($e) { //do something ... }
    
    0 讨论(0)
  • 2020-12-05 02:52

    You can also target any element without @hostlistener and can add necessary events by the following way

    import { AfterViewInit, Component, ElementRef} from '@angular/core';
    
    constructor(private elementRef:ElementRef) {}
    
    ngAfterViewInit() {
      this.elementRef.nativeElement.querySelector('my-element')
                                    .addEventListener('click', this.onClick.bind(this));
    }
    
    onClick(event) {
      console.log(event);
    }
    
    0 讨论(0)
提交回复
热议问题