Search code examples
angularlifecycle

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


Solution

  • <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