How do I detect a browser or tab closing using hostlistener in Angular?

1 minute read

There is no built-in way to detect when the browser or tab is closed in Angular, but you can use the window object’s ‘beforeunload’ event to trigger an event before the browser tab closes.

In the below sample code, we have used the ‘hasChanges()’ method to return the ‘true’ status so that the unload event won’t allow the user to close the tab. You can show the confirmation popup to ask the user whether they want to close the tab and proceed based on their confirmation because it will prevent the user from accidentally closing the tab when important details are loaded in the tab.


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

  selector: 'app-root',
  template: `
    <h1>Close this tab to trigger the event</h1>
export class AppComponent {
  * Triggers when user closes the browser tab / browser window and prevent from closing when there any pending changes.
  * @param event
  @HostListener('window:beforeunload', ['$event'])
  public beforeunloadHandler(event: any) {
      if (hasChanges()) {
          event.returnValue = false;

  * Detect the changes
    return true;

Leave a comment