Is there any lifecycle hook like window.onbeforeunload in Angular2? I already googled and searched on stackoverflow, but found nothing
9 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

- 38,872
- 15
- 103
- 162

- 623,577
- 216
- 2,003
- 1,567
-
What about the `window.onbeforeunload` approach? How does it not work? – Günter Zöchbauer Apr 21 '16 at 09:28
-
13Unfortunatelly, all 3 options dont work. Does it have to be on the parent component? On the child component, it doesnt fire the event. Example : window.onbeforeunload = function (e) { alert('Event triggered!');} – Dieter Köberl Apr 21 '16 at 09:30
-
1I updated my question. The code (last variant) shows the dialog when I navigate away from the page in Chrome. – Günter Zöchbauer Apr 21 '16 at 09:38
-
How would I go about only showing the dialogue if some property of the component is true? – oddRaven Aug 17 '16 at 23:03
-
1@oddRaven check out my answer below – Aviad P. Aug 29 '16 at 19:58
-
2Chrome no longer supports custom strings: https://www.chromestatus.com/feature/5349061406228480 – Brian Aug 03 '17 at 19:29
-
3In Angular 4, the top solution withworked for me. In my case I wanted to perform a user logout if the window or all tabs were closed.– aspergillusOryzae Mar 13 '18 at 02:55
-
1The HostListener didn't work for me (it always prompted me irregardless of whether the page had changes) and the only thing I found to get this to work was using router-outlet. See https://stackoverflow.com/a/51145053/2525272. – sfors says reinstate Monica Feb 13 '19 at 16:49
-
How could you test if this even works? AKA, if I navigate away from the page to make window.unload fire, how do I know my function ran? Console.logs wont work bc the app is destroyed. You guys mentioned a dialogue text, but I'm not sure if or where that would be read.. – Kyle Vassella Jul 08 '19 at 15:17
-
Sorry, don't remember. I only investigated it for this question back then and haven't used it myself anywhere since. – Günter Zöchbauer Jul 08 '19 at 15:19
-
@KyleVassella Maybe a year late, but you can activate 'preserve log' option in the console and then it won't remove the log statements. – Brudus Aug 13 '20 at 07:44
-
1@GünterZöchbauer Awesome, I used step 3 and it worked perfectly fine. Thank you – Thiagz Mar 18 '21 at 11:59
-
Not works version 10 – Alam Nov 28 '21 at 15:25
-
Works only if you have interacted at least once with the web page (like clicked some button or entered something on the page). Otherwise it will never stop on this listener. – Pawan Pillai Feb 22 '22 at 17:00
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:
The argument to@HostListener
should bewindow:beforeunload
and notwindow:onbeforeunload
- The handler shouldn't return the message, but should assign it into
$event.returnValue
instead

- 32,036
- 14
- 103
- 124
-
This code works for me. Unfortunately, this does not execute in my android phone when I close the tab. Any suggestions? – brijmcq May 01 '17 at 06:17
-
1https://stackoverflow.com/questions/35779372/window-onbeforeunload-doesnt-trigger-on-android-chrome-alt-solution might help – Günter Zöchbauer Aug 04 '17 at 07:22
-
a dialog shows when the `returnValue` is anything but `null`. And most broswers dispaly a generic message to the user now. So you are not able to change it. – Martin Schneider Dec 03 '17 at 20:43
-
4[returnValue is supposed to be a boolean](https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue) – Flavien Volken Dec 18 '17 at 22:05
-
12October 2018 update, Angular 6: Needed to set `$event.returnValue=true;`. Any other value didn't work (false, null, string etc.). – Marty131 Oct 23 '18 at 02:56
-
@Marty131 so you set `$event.returnValue` to `true` and return the actual string message? – Aviad P. Oct 23 '18 at 10:45
-
@Marty131 the update you mentioned is wrong - if not in theory then in practice - check out this stackblitz: https://stackblitz.com/edit/angular-ug2rgv – Aviad P. Nov 15 '18 at 20:03
-
@AviadP. - If I attempt to close the StackBlitz tab you linked, it closes without any prompt. I am using Chrome on Windows 10. If I modify returnValue = true, then it will prompt me when closing tab/window. What browser and OS is it working for you? – Marty131 Nov 19 '18 at 02:10
-
1Returning a string works for me in Chrome: `@HostListener('window:beforeunload', ['$event']) handleUnload(e) { e.preventDefault(); e.returnValue = 'Wait!';}` – Christian Jensen Jul 23 '19 at 18:44
-
-
error TS2339: Property 'hasChanges' does not exist on type component.ts – Himanshu Bansal May 14 '20 at 08:14
-
`hasChanges` is a property you should implement to return `true` if the view is 'dirty' – Aviad P. May 14 '20 at 09:41
-
there is any way to add `if` to this argument? something like that `$event.returnValue = !!this.numberOfRequests;` – Kordrad Aug 12 '21 at 10:37
-
Works only if you have interacted at least once with the web page (like clicked some button or entered something on the page). Otherwise it will never stop on this listener. – Pawan Pillai Feb 22 '22 at 17:00
-
Is there any way to find out if the page is being refreshed or closed? I want to execute my script Tab/browser being closed. – Awesh Vishwakarma Apr 06 '22 at 08:30
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).
-
6**Work only if the user interract with the page (e.g. click).** I kept refreshing the page thinking it does not work – umutesen Feb 17 '20 at 21:00
-
Used this in my service where I need to make sure that critical section managed by localStorage is reopened when tab acquires lock and is closed at the same time (e.g. `localStorage.removeItem()`) – sax May 05 '20 at 10:24
-
Thanks Nicolas, thanks Umutesen. Nicolas' function works perfectly, but you have to realize what Umutesen says; it only works if the user interacts with the page. (Which is actually PERFECTO) – James Ikubi Feb 20 '22 at 15:45
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')

- 140,023
- 84
- 646
- 689
-
1On desktop chrome it works perfectly: `@HostListener('window:pagehide', ['$event']) onClose($event) { console.log('hello') } ` So you don't need to use both – Francisco Bueno Aug 04 '20 at 11:37
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;
}

- 1,154
- 7
- 18
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

- 41
- 4
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
.

- 2,552
- 25
- 18
According to the chrome documentation here: https://developer.chrome.com/blog/page-lifecycle-api/#the-beforeunload-event most of the answers here are ill advised for it prevents browsers from caching the page in their Back-Forward Cache.
The listener should be conditionally added and removed depending on whether some changes need to be saved or not. An example is provided in the link as well.

- 361
- 3
- 4
You just need to add **beforeunload** in the component, Initialize when its require or in ngOnInit and at last, add remove even listener so its not effect pages of the application.
@Component({
host: { 'window:beforeunload': '' },
})
ngOnInit(){
window.addEventListener('beforeunload', this.checkLoad, false);
}
checkLoad(event) {
event.preventDefault();
event.returnValue =
'Are you sure you want to discard the form? Your process will be lost.';
return event;
}
ngOnDestroy(){
window.removeEventListener('beforeunload', this.promptIfSureToRedirect, false);

- 1
- 2