Here is a quick code snippet that I got from a collegae on how to prevent a user from navigating away from a page.
In our situation we want to avoid that a user forgets to save his changes and therefore want to show an explicit warning. This is not that hard to to in Angular thanks to the availability of the @HostListener decorator:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
canDeactivate(): boolean { // | Promise<boolean> | Observable<boolean> { | |
if (this.mainForm.dirty) { | |
return this.dialogService.confirm('There are unsaved changes. Do you want to continue without saving?'); | |
} else { | |
return true; | |
} | |
} | |
// @HostListener allows us to also guard against browser refresh, close, etc. | |
@HostListener('window:beforeunload', ['$event']) | |
unloadNotification($event: any) { | |
if (!this.canDeactivate()) { | |
$event.returnValue = "This message is displayed to the user in IE and Edge when they navigate without using Angular routing (type another URL/close the browser/etc)"; | |
} | |
} |