0

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?

rbasniak
  • 4,484
  • 11
  • 51
  • 100
  • Have you tried this: https://stackoverflow.com/questions/27367728/detecting-page-unload-in-angularjs – Gustavo Jantsch Aug 01 '17 at 17:48
  • `window.unload` is fired after the DOM contents are removed. That means the component has been destroyed. – Reactgular Aug 01 '17 at 17:52
  • @GustavoJantsch That question is for AngularJs, I'm using Angular 4, but it's the same event that I hooked to. This event defines wheter the confirmation popup will show or not, but after that I don't know if the user cancel or confirmed that popup. – rbasniak Aug 01 '17 at 17:54

0 Answers0