Is there any lifecycle hook like window.onbeforeunload in Angular2?

AngularLifecycle

Angular Problem Overview


Is there any lifecycle hook like window.onbeforeunload in Angular2? I already googled and searched on stackoverflow, but found nothing

Angular Solutions


Solution 1 - Angular

<div (window:beforeunload)="doSomething()"></div>

or

@Component({ 
  selector: 'xxx',
  host: {'window:beforeunload':'doSomething'}
  ..
)}

or

@Component({ 
  selector: 'xxx',
  ..
)}
class MyComponent {
  @HostListener('window:beforeunload')
  doSomething() {
  }
}

This is how to listen to global events. I don't know if the special behavior of this event is supported where the return value is used as text for the conformation dialog.

You can still use

export class AppComponent {  
  constructor() {
    window.onbeforeunload = function(e) {
      return 'Dialog text here.';
    };
  }
}

Like explained here https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Solution 2 - Angular

Günter Zöchbauer's answer is slightly wrong on two one count, this is what worked for me:

@Component({ 
  selector: 'xxx',
  ..
)}
class MyComponent {
  @HostListener('window:beforeunload', ['$event'])
  doSomething($event) {
    if(this.hasChanges) $event.returnValue='Your data will be lost!';
  }
}

There are two main differences from Günter's answer:

  1. The argument to @HostListener should be window:beforeunload and not window:onbeforeunload
  2. The handler shouldn't return the message, but should assign it into $event.returnValue instead

Solution 3 - Angular

This worked for me. Defined in the page component constructor

window.addEventListener("beforeunload", (event) => {
   event.preventDefault();
   event.returnValue = "Unsaved modifications";
   return event;
});

Define the returnValue only if you want to prompt user before unload.

Work only if the user interract with the page (e.g. click).

Solution 4 - Angular

Important note for iOS

The beforeunload event isn't supposed - presumably due to the high level of 'abuse' over the years.

Instead you can use pagehide as recommended by Apple.

This is part of the Page visibility API.

https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

So I can't seem to get pagehide to fire on desktop chrome, and I can't get beforeunload to fire on iOS Safari - so you need both - but make sure not to fire your code twice.

@HostListener('window:beforeunload')
@HostListener('window:pagehide')

Solution 5 - Angular

In angular we can create something like this.

@HostListener('window:beforeunload')
confirmLeavingPageBeforeSaving(): boolean {
  // if 0 display dialog
  // if 1 you can reload
  return !this.myBoolean; 
}

Solution 6 - Angular

This is more of an added note than an answer but I can't really comment right now.
Still, I wanted to add this:

I wouldn't say it's too complicated of initialization logic, but if you do decide to add the event listener on component initialization it would be best to include this in ngOnInit rather than the constructor:

window.addEventListener('beforeunload', function (e) {
  e.preventDefault();
  e.returnValue = '...';
});

This is especially if you are including additional logic before unload.

There's also a good article on ngOnDestroy which works similarly to a destructor for directives, pipes, and services. Both approaches are convenient depending on what operations you wish to perform.

Full link text:
https://wesleygrimes.com/angular/2019/03/29/making-upgrades-to-angular-ngondestroy.html

credit to Günter Zöchbauer's original answer

Solution 7 - Angular

If one is looking for how to add and remove the listener.

 ngOnInit(){
  /*
   * Ask user if they are sure they want to refresh
    * -> Works only if the user interacts with the page (e.g. click).
  */
   window.addEventListener('beforeunload', this.promptIfSureToRedirect, false);
 }

promptIfSureToRedirect(event) {
    event.preventDefault();
    event.returnValue = 'Changes you made may not be saved.';
    return event;
}


 ngOnDestroy(){
   window.addEventListener('beforeunload', this.promptIfSureToRedirect, false);
 }

In a component, listen to the event "beforeunload", then pass a function that will be called before unload. On Destroy, remove this listener by passing the same function used to listen.

// -> I would like to big up @Nicolas and @Umutesen for the pointers

Other pointers:

-> Be sure to work with the event listener in the "window" element, don't interchange with document; e.g document.addEventListener.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDieter K&#246;berlView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularAviad P.View Answer on Stackoverflow
Solution 3 - AngularNicolasView Answer on Stackoverflow
Solution 4 - AngularSimon_WeaverView Answer on Stackoverflow
Solution 5 - AngularKordradView Answer on Stackoverflow
Solution 6 - AngularSECView Answer on Stackoverflow
Solution 7 - Angularjames aceView Answer on Stackoverflow