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

Dieter Köberl picture Dieter Köberl · Apr 21, 2016 · Viewed 66.2k times · Source

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

Answer

Günter Zöchbauer picture Günter Zöchbauer · Apr 21, 2016
<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