I have angular application with angular reactive forms. I want to warn users when closing the browser tab/window based on some condition.
How do I achieve that?
I tried the following but it always shows the warning message regardless of what I return or what condition I use. I have the following in the component.ts file:
@HostListener('window:unload', ['$event']) handleClose($event: Event) {
$event.returnValue = false;
if (!this.myForm.pristine) {
$event.preventDefault();
return false;
}
else return true;
}
And the following in the component.html file
<div (window:beforeunload)="handleClose($event)"></div>
What I want to do is check for a condition to show/not show the warning pop up. Much appreciated.
CodePudding user response:
try this
@HostListener('window:beforeunload', ['$event'])
handleClose($event): void {
if (!this.myForm.pristine) { // prevent unload event action.
$event.returnValue = true;
}
}