How to use @HostListener in Angular

How to use @HostListener in Angular

If you add @HostListener to your event handler, it will listen for events all the time.

The following listens for an event handler to be executed when clicked anywhere in the browser.


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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  // Write @HostListener on top of the event handler
  @HostListener( 'document:click', [ '$event' ] )
  public onTest(event: Event) {



By writing, an event handler will be executed when the user clicks anywhere in the browser.

On the HTML side, you do not need to write (click) at all.

Event Event handler operation details
@HostListener( ‘document:click’, [ ‘$event’ ] ) When clicking anywhere in the browser
@HostListener( ‘document:mouseover’, [ ‘$event’ ] ) On mouse-over in the browser
@HostListener( ‘window:resize’, [ ‘$event’ ] ) When the browser is resized