Is there any lifecycle hook like [removed] in Angular2?

前端 未结 5 892
清歌不尽
清歌不尽 2020-11-27 14:19

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

5条回答
  •  失恋的感觉
    2020-11-27 15:06

    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

提交回复
热议问题