40

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?

georgej
  • 3,041
  • 6
  • 24
  • 46

2 Answers2

55

On refresh or when you navigate away from the current page (except for routing), 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

Jnr
  • 1,504
  • 2
  • 21
  • 36
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 3
    Does component gets destroyed when the browser is closed? – Ritesh Waghela Aug 03 '17 at 08:07
  • 2
    @Ritesh no, only when Angular itself destroy it and it won't have time anymore when the browser is closed. See also https://stackoverflow.com/questions/37642589/how-can-we-detect-when-user-closes-browser/37642657#37642657 – Günter Zöchbauer Aug 03 '17 at 08:08
  • 1
    Yes, I did verify this behavior. Thanks. – Ritesh Waghela Aug 07 '17 at 11:25
  • @GünterZöchbauer What do you mean by 'because you move away'? How does it differ from 'navigate away from the current page'. – Mac_W Mar 27 '18 at 13:34
  • The difference is whether the Angular router shows a different content on the same page or a different page is loaded. In the later case there is nothing Angular can do because the browser just kills it. – Günter Zöchbauer Mar 27 '18 at 13:37
  • @GünterZöchbauer how to identify if it is same page or different page loaded? – srikanth_k Jun 11 '18 at 15:58
  • @srikanth_k sorry, but I don't understand your question. A different page is a different application. What do you want to identify from where? – Günter Zöchbauer Jun 11 '18 at 16:01
  • 3
    @GünterZöchbauer,I navigated to some /xyz path which loads a component with ngOnDestroy. When I am manually changing browser url to root path ('/'), ngOnDestroy is not getting called. – srikanth_k Jun 11 '18 at 16:04
-3

You can do one thing and it works like a charm. Create a test guard and apply on your component.

Create a service with a BehavioralSubject. and whenever go to your component the guard will check and in the guard initialize your subject, as and when it gets initialized it will check if it is getting subscribed somewhere. In your component in the ngOnInit subscribe to this subject and from there call the destroy method.