Is there any lifecycle hook like window.onbeforeunload in Angular2? I already googled and searched on stackoverflow, but found nothing
This is more of an added note than an answer but I can't really comment right now.
Still, I wanted to add this:
I wouldn't say it's too complicated of initialization logic, but if you do decide to add the event listener on component initialization it would be best to include this in ngOnInit rather than the constructor:
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '...';
});
This is especially if you are including additional logic before unload.
There's also a good article on ngOnDestroy which works similarly to a destructor for directives, pipes, and services. Both approaches are convenient depending on what operations you wish to perform.
Full link text:
https://wesleygrimes.com/angular/2019/03/29/making-upgrades-to-angular-ngondestroy.html
credit to Günter Zöchbauer's original answer