Angular Renderer2 remove listener

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?


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();
    }
  }
}