Call a function when user closes tab in angular

Viewed 748

I would like to call a function when user closes the tab. I have used hostlistener to fire a event when user closes the tab and a popup appears with cancel and leave button. I need to call a function when user clicks the leave button. Below is the code I have written and I need to call myFunction() when user clicks on leave button.

@HostListener('window:beforeunload', ['$event'])
 beforeunloadHandler(event) {
 event.preventDefault();
 return false;   
}

myFunction(){
 //code
}
2 Answers

You can try ngOnDestroy if you are changing tab then this method will invoke and you can call your function!!

ngOnDestroy(): void { enter code here }

There are two ways to the listener to the event of closing tab in your class, by calling your function with the key this.

 @HostListener('window:unload', [ '$event' ])
   beforeUnloadHandler(event) {
   this.myFunction(event)
   event.preventDefault();
   return false;   
  }
  unloadHandler(event) {
    this.myFunction(event)
    // ...
  }

 
  

myFunction(event){
 console.log("this event come form: ", event)
}
Related