Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Renderer2 remove listener

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?

like image 524
Serginho Avatar asked Jun 09 '17 09:06

Serginho


People also ask

When should I use Renderer2?

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.

What is Angular Renderer2?

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.

What is addEventListener in Angular?

addEventListener()linkRegisters a handler for a specific element and event. addEventListener(element: HTMLElement, eventName: string, handler: Function): Function.


2 Answers

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();
    }
  }
}
like image 57
yurzui Avatar answered Sep 20 '22 13:09

yurzui


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?

like image 37
slaesh Avatar answered Sep 18 '22 13:09

slaesh