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

痴心易碎 提交于 2019-11-26 08:09:24

问题


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


回答1:


<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/de/docs/Web/API/WindowEventHandlers/onbeforeunload




回答2:


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



回答3:


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')



回答4:


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).



来源:https://stackoverflow.com/questions/36763141/is-there-any-lifecycle-hook-like-window-onbeforeunload-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!