If we want to add event listener to any element we can do it through event binding in Components or by using a Directive. But, sometimes we may want to add event listener to the entire document of the application.  Since document is not a single element, we cannot add event listener to it using the regular event binding methods.However we can add event listener to the document in multiple ways in Angular 12.

1. Adding Event listener to document in Angular 12 – Vanilla JavaScript way:

This is regular JavaScript DOM way of adding event listener. There is nothing Angular specific thing in this way. We can directly access the document inside a component and add event listener to it. This can be done preferably inside AppComponent, since this is the component that loads first. If you want to add inside any other component, make sure that the component is getting created or the event may not get registered on the document.

example:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'howtoJS - Angular';
  constructor() {
    document.addEventListener('click', (clickEvent: MouseEvent) => {
      console.log('Click Event Details: ', clickEvent)
    })
  }

}

Though we can do like this, this is not recommended. When we are using any framework such as Angular, which handles the DOM through the framework, it is not recommended to directly interact with the DOM.

2. Adding Event Listener to document in Angular 12 – Using HostListener :

We can use the built-in HostListener decorator which listens to the events of the Host of the component/directive. Since document hosts the AppComponent, we can listen to the document events using this decorator.

example:

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'howtoJS - Angular';
  @HostListener('document:click', ['$event']) documentClickEvent($event: MouseEvent) {
    console.log('Through HostListener - Click Event Details: ', $event)
  }
  constructor() {
  }

}

3. Adding Event Listener to document in Angular 12 – Using Host:

We can also add event listener to document by using the host property of Component decorator.

example:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  host: { ['(document:click)']: 'documentClickEvent($event)' }
})
export class AppComponent {
  title = 'howtoJS - Angular';
  constructor() {
  }
  documentClickEvent($event: MouseEvent) {
    console.log('Through Host - Click Event Details: ', $event)
  }

}