I need to add some logic in angular component before user navigates away from the page. Trying a few suggestions after googling possible solutions but nothing seems to work for me. I tried this option (does not work when user leaves the page):
@HostListener('window:onbeforeunload', ['$event'])
unloadHandler() {
event.preventDefault();
alert('leave?');
}
Also tried this in html (neither works):
<div (window:onbeforeunload)="unloadHandler()"></div>
Could someone advice something?
CodePudding user response:
DeactivateGuard is what you need.
check this stackblitz
https://stackblitz.com/edit/candeactivate
this link used it inside component but you can define generic deactivate guard and use it in your routing array.
https://stackblitz.com/edit/clabnet-angular-candeactivate?file=app/app.routing.module.ts
CodePudding user response:
Actually you should return value there and correct syntax, that's result you want:
@HostListener('window:beforeunload', ['$event'])
unloadHandler() {
event.preventDefault();
alert('leave?');
return false;
}
CodePudding user response:
Implement ngOnDestroy() and add your code in that method