I'm using Angular 4 on my project and in some pages I need to do some cleaning if the user leaves the page without saving the data. I can achieve this using ngOnDestoy()
, but it only works when the user is navigating away from the page using the links in it.
To warn them about unsaved changes when they try to press F5, tries to navigate to another domain or close the tab, I'm using the following code:
@HostListener('window:beforeunload', ['$event'])
public beforeunload($event)
{
if (this.hasChanges)
{
return false;
}
}
This code shows a default browser popup to ask the user if they really want to leave the page. If they don't want to, that's ok, I don't have to do anything. But it they decide they don't care about the unsaved data, then I have to do the cleaning.
I saw that there's an [unload][1]
method in the window
object, and I tried something like this:
@HostListener('window:unload', ['$event'])
public unload($event)
{
// do some cleaning...
}
But this event is never fired. Am I doing something wrong, or there's another way to do this?