I have the following implementation of a directive. How to removeEventListener in this case:
import { Directive, ElementRef, OnDestroy } from \"@angular/core
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:
Working DEMO: https://plnkr.co/edit/ZYnlruYQ2HwrQpHZqV9O?p=preview
NOTE: In DEMO, I use blur event instead of ngDestroy. (which serve the same purpose). If you type anything in textbox, it will listen to keyup event but as you come out from textbox input , blur event happens and no further keyup will get fired.
import { Directive, ElementRef, OnDestroy } from "@angular/core";
@Directive({
selector: "[Enter]"
})
export class Enter implements OnDestroy{
constructor(el: ElementRef) {
var button=el.nativeElement;
button.addEventListener('keyup',this.error)
}
error(event){
console.log(event);
//whatsoever
if(event.keyCode === 13){
el.nativeElement.click();
}
}
ngOnDestroy(){
button.removeEventListener('keyup',this.error);
}
}
This should solve the problem:
import { Directive, ElementRef, OnDestroy } from "@angular/core";
@Directive({
selector: "[Enter]"
})
export class Enter implements OnDestroy{
private enter;
constructor(el: ElementRef) {
this.enter = function(event){
if(event.keyCode === 13){
el.nativeElement.click();
console.log("enter triggered");
}
}
document.addEventListener('keyup', this.enter , false);
console.log("Added event listener");
}
ngOnDestroy(){
document.removeEventListener('keyup', this.enter, false);
console.log("Removed event listener");
}
}
Hope this helps.
Cheers, SZ
As of today, the "Angular way" is to inject a Renderer2
dependency and work with that, to abstract away actual DOM manipulation when working on a platform different than browser (e.g. native or server-side rendering).
See this SO answer.
Make it like this:
import { Directive, ElementRef, OnDestroy } from "@angular/core";
@Directive({
selector: "[Enter]"
})
export class Enter implements OnDestroy{
private enter: (event: KeyboardEvent) => void;
constructor(el: ElementRef) {
this.enter = (event) => {
if(event.keyCode === 13){
el.nativeElement.click();
}
}
document.addEventListener('keyup', this.enter , false);
}
ngOnDestroy(){
document.removeEventListener('keyup', this.enter, false);
}
}