Angular: Using a service to listen to DOM events

In an Angular Component or a Directive, you can use the @HostListener decorator to listen to DOM events e.g.:

@HostListener('document:click', ['$event'])
private onClick(event: Event) {
    ...
}

Using the decorator is very convenient. Unfortunately, it doesn’t work in Angular services. In a service, you have two options:

  1. Using window.addEventListener
  2. Using rxjs fromEvent

The first option looks like this:

document.addEventListener('click', () => {
    ...
});

With the second option, it looks more angular-ishy:

import { fromEvent } from 'rxjs';

...

fromEvent(document, 'click').subscribe(() => {
  ...
});

In order to test this (no matter which option, you’ve chosen above), you just need to do the following:

document.dispatchEvent(new MouseEvent('click'));