'How to detect browser close event or tab close event in angular 6+?

I have written @HostListener in my AppComponent Class to detect browser close or tab close.

I have written this code but it is not working. Kindly help me understand why my code is not working

Below is my code.

export class AppComponent {

  @HostListener('window:unload', [ '$event' ])
  unloadHandler(event) {
    alert('call unload');
  }

  @HostListener('window:beforeunload', [ '$event' ])
  beforeUnloadHander(event) {
    alert('call beforeunload');
  }
}


Solution 1:[1]

use Angular guard, There are 5 types of guards in Angular namely CanActivate, CanActivateChild, CanDeactivate, Resolve and CanLoad

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mukesh Kumar Mehta