Angular 2 - Does ngOnDestroy get called on refresh or just when navigate away from component?

Solution 1:

On refresh or when you navigate away from the current page, then ngOnDestroy won't be called. The application will just be destroyed by the browser.

Only when Angular2 removes the component from the DOM because you move away or you call destroy() on a dynamically created component, then ngOnDestroy() is called.

You can listen to beforeunload and unload yourself if you need some action to happen before the application is destroyed by the browser.

See also

  • https://developer.mozilla.org/en-US/docs/Web/Events/unload
  • How can we detect when user closes browser? (Angular)