Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 575
Dieter Köberl Avatar asked Apr 21 '16 07:04

Dieter Köberl


People also ask

What is the difference between Onbeforeunload and Onunload?

Prototype: Whereas unload is a normal event that inherits from Event , beforeunload has its own prototype, BeforeUnloadEvent .

What triggers Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What does Window Onbeforeunload do?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.


2 Answers

<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

like image 168
Günter Zöchbauer Avatar answered Sep 23 '22 23:09

Günter Zöchbauer


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
like image 40
Aviad P. Avatar answered Sep 23 '22 23:09

Aviad P.