Is it possible to remove listeners with the new angular 4 renderer?
here is the interface:
abstract listen(target: 'window' | 'document' | 'body' | any, eventName: string, callback: (event: any) => boolean | void): () => void;
In the renderer v1 listen and listenGlobal returns a Function, but this one returns void.
Is it an issue? If not, how can I remove a listener?
The Renderer2 allows us to manipulate the DOM elements, without accessing the DOM directly. It provides a layer of abstraction between the DOM element and the component code. Using Renderer2 we can create an element, add a text node to it, append child element using the appendchild method., etc.
The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly.
addEventListener()linkRegisters a handler for a specific element and event. addEventListener(element: HTMLElement, eventName: string, handler: Function): Function.
There is no difference with Renderer
:
import { Renderer2 } from '@angular/core';
export class MyComponent {
listenerFn: () => void;
constructor(private renderer: Renderer2) {}
ngOnInit() {
this.listenerFn = this.renderer.listen(document, 'mousemove', () => console.log('move'));
}
ngOnDestroy() {
if (this.listenerFn) {
this.listenerFn();
}
}
}
You could also use the fromEventPattern
function from rxjs.
private createOnClickObservable(renderer: Renderer2) {
let removeClickEventListener: () => void;
const createClickEventListener = (
handler: (e: Event) => boolean | void
) => {
removeClickEventListener = renderer.listen("document", "click", handler);
};
this.onClick$ = fromEventPattern<Event>(createClickEventListener, () =>
removeClickEventListener()
).pipe(takeUntil(this._destroy$));
}
just use/subscribe to it as expected
myMouseService.onClick$.subscribe((e: Event) => {
console.log("CLICK", e);
});
and dont worry about destroying, it will be handled by rxjs during closing the observable!
live-demo: https://stackblitz.com/edit/angular-so4?file=src%2Fapp%2Fmy-mouse.service.ts
see another answer, to explore more details: Is it possible to use HostListener in a Service? Or how to use DOM events in an Angular service?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With