I would like to warn users of unsaved changes before they leave a particular page of my angular 2 app. Normally I would use window.onbeforeunload
, but that doesn't work for single page applications.
I've found that in angular 1, you can hook into the $locationChangeStart
event to throw up a confirm
box for the user, but I haven't seen anything that shows how to get this working for angular 2, or if that event is even still present. I've also seen plugins for ag1 that provide functionality for onbeforeunload
, but again, I haven't seen any way to use it for ag2.
I'm hoping someone else has found a solution to this problem; either method will work fine for my purposes.
Best Answer
To also cover guards against browser refreshes, closing the window, etc. (see @ChristopheVidal's comment to Günter's answer for details on the issue), I have found it helpful to add the
@HostListener
decorator to your class'scanDeactivate
implementation to listen for thebeforeunload
window
event. When configured correctly, this will guard against both in-app and external navigation at the same time.For example:
Component:
Guard:
Routes:
Module:
NOTE: As @JasperRisseeuw pointed out, IE and Edge handle the
beforeunload
event differently from other browsers and will include the wordfalse
in the confirm dialog when thebeforeunload
event activates (e.g., browser refreshes, closing the window, etc.). Navigating away within the Angular app is unaffected and will properly show your designated confirmation warning message. Those who need to support IE/Edge and don't wantfalse
to show/want a more detailed message in the confirm dialog when thebeforeunload
event activates may also want to see @JasperRisseeuw's answer for a workaround.