0

I manually add and remove Eventlisteners on DOM-Elements for performance reasons from the ngZone in Angular. My implementation seems fine and I'm currently try to refactor code to keep it DRY and more readable. Now, my question is if there is a way to pass multiple DOM-Elements to the Renderer2.listen() function. So basically I want to do something like this:

this._unlisten['mouseup'] = this._renderer.listen(
   this.elementView.nativeElement, // <- Can I pass more elements than just elementView?
   'mouseup',
   (event) => {
       unlistenToTheEventOnSeveralElements(event)
   }
)

Thanks in advance for any ideas or suggestions.

metodribic
  • 1,561
  • 17
  • 27

1 Answers1

0

From an Angular documentation:

The context in which to listen for events. Can be the entire window or document, the body of the document, or a specific DOM element.

If you need to listen to a multiple elements being clicked you should use rxjs fromEvent and merge all events with merge like this:

merge(fromEvent(firstElement, 'click'), fromEvent(secondElement, 'click'))
  .pipe(takeUntil(/* destroy subject */)
  .subscribe(event => unlistenToTheEventOnSeveralElements(event))

Here is the example app so you can see it in action: stackblitz

metodribic
  • 1,561
  • 17
  • 27