Removing EventListener in ngOnDestroy

后端 未结 5 1593
别跟我提以往
别跟我提以往 2021-01-04 18:56

I have the following implementation of a directive. How to removeEventListener in this case:

import { Directive, ElementRef, OnDestroy } from \"@angular/core         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 19:11

    I would leverage @HostListener decorator to do that:

    @Directive({
      selector: "[Enter]"
    })
    export class Enter {
      @HostListener('document:keyup', ['$event'])
      enter(event) {
        if (event.keyCode !== 13) return;
        this.el.nativeElement.click();
      }
      constructor(private el: ElementRef) { }
    } 
    

    The handler will be automatically removed in ngOnDestroy.

    For other solutions see:

    • How to listen for mousemove event on Document object in Angular

提交回复
热议问题