30

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?

Serginho
  • 7,291
  • 2
  • 27
  • 52

3 Answers3

76

There is no difference with Renderer:

import { Renderer2 } from '@angular/core';

export class MyComponent {
  listenerFn = () => {};

  constructor(private renderer: Renderer2) {}

  ngOnInit() {
    this.listenerFn = this.renderer.listen(document, 'mousemove', () => console.log('move'));
  }

  ngOnDestroy() {
    this.listenerFn();
  }
}
Aqeel Ashiq
  • 1,988
  • 5
  • 24
  • 57
yurzui
  • 205,937
  • 32
  • 433
  • 399
1

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?

slaesh
  • 16,659
  • 6
  • 50
  • 52
0

It’s easier to put the result of the Renderer.listen handler in a variable:

listener: any;

this.listener = this.renderer.listen('body', 'mousemove', (event) => {
  console.log(event);
});

and when the cancel event occurs, call the variable with empty parameters

this.renderer.listen('body', 'mouseup', (event) => {
  this.listener();
});
Sjupj
  • 1