How can I use @HostListener('window:beforeunload') to call a method?
Try like this :
@HostListener('window:unload', ['$event'])
unloadHandler(event) {
this.PostCall();
}
@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander(event) {
return false;
}
PostCall() {
console.log('PostCall');
}
window:beforeunload
is a browser event which is triggered right before actually unloading the page.
When you navigate to another component, you are not actually unloading the page.
What you need to do is use ngOnDestroy
which will be called when component is being destroyed. Implements the following interface:
https://angular.io/api/core/OnDestroy
Example:
export class NewComponent implements OnDestroy{
ngOnDestroy() {
PostCall();
}
}