1

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');
  }
}
Adnan Sheikh
  • 760
  • 3
  • 13
  • 27
Jigar Prajapati
  • 93
  • 1
  • 10
  • 2
    Possible duplicate of [Is there any lifecycle hook like window.onbeforeunload in Angular2?](https://stackoverflow.com/questions/36763141/is-there-any-lifecycle-hook-like-window-onbeforeunload-in-angular2) – TmTron Mar 16 '19 at 16:18
  • 1
    Possible duplicate of [Detect browser or tab closing](https://stackoverflow.com/questions/3888902/detect-browser-or-tab-closing) – Liam Jun 24 '19 at 10:39

1 Answers1

0

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

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31298417) – Tom Mar 18 '22 at 09:34