Is there any lifecycle hook like window.onbeforeunload in Angular2? I already googled and searched on stackoverflow, but found nothing
Prototype: Whereas unload is a normal event that inherits from Event , beforeunload has its own prototype, BeforeUnloadEvent .
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.
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.
<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
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:
@HostListener
should be window:beforeunload
and not window:onbeforeunload
$event.returnValue
insteadIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With