Is there any lifecycle hook like window.onbeforeunload in Angular2? I already googled and searched on stackoverflow, but found nothing
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:
@HostListener
should be window:beforeunload
and not window:onbeforeunload
$event.returnValue
instead