Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 702
georgej Avatar asked Nov 07 '16 15:11

georgej


People also ask

Is ngOnDestroy called on refresh?

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.

What is true about ngOnDestroy?

ngOnDestroy()link A callback method that performs custom clean-up, invoked immediately before a directive, pipe, or service instance is destroyed.

Can we use ngOnDestroy in service?

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.


1 Answers

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)
like image 109
Günter Zöchbauer Avatar answered Oct 23 '22 12:10

Günter Zöchbauer