I am trying to figure out if ngOnDestroy in Angular 2 gets ran on a refresh or just when someone navigates away from the page?
It is used for unsubscribing to events and handling any teardown events before destroying the component/service. Although we have plenty of faith in ngOnDestroy to accomplish these things, there are times where ngOnDestroy will actually fail you. For 4 navigation events, ngOnDestroy will not be called: Page Refresh.
ngOnDestroy()link A callback method that performs custom clean-up, invoked immediately before a directive, pipe, or service instance is destroyed.
The surprise was that each of those methods were never called inside the App itself. As it turns out, ngOnDestroy works not only on Component or Directive, it is also usable for Service and Pipe.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With