2

So I checked official documentation about life cycle hook ngOnDestroy() and I get the fact it gets called on Component or Service, Pipe etc destroy. I also checked this guide here which also explains how to handle such situation correctly: https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/

But fundamentally I don't understand when Angular (2+) actually destroys Components? what are practical events that take place that lead to Component destruction?

Sorry I have no computer science background and probably the answer is very obvious.

Sergey Rudenko
  • 8,809
  • 2
  • 24
  • 51
  • Destroy means in simple form that angular remove its element from DOM. Probably you can get answer from this [link](https://stackoverflow.com/a/46694186/2919078) – Gautam Sep 12 '18 at 02:41
  • Thanks! The article is interesting but is not a direct full answer since services in angular for instance dont get to DOM etc and i want to know the insides of this. – Sergey Rudenko Sep 12 '18 at 05:41
  • Services in angular are different from Component, but if you added provider[service] in your component and as soon as the component destroy then the service also destroyed but if the service used in app.module provide[service] then this service will remain without destroy entirely. For more information follow [link](https://stackoverflow.com/questions/45898948/angular-4-ngondestroy-in-service-destroy-observable) . If you want to go deepest then u need to have good overview of DOM and Injector pattern, etc. – Gautam Sep 12 '18 at 06:17

1 Answers1

1

Usually it is when your using the router and navigating around your app. That way you don't use up all the resources by keeping stuff in memory. It is also a good way to subscribe and unsubscribe to observables.

when using *ngIf the component also gets destroyed between each show/hide.

Leon Radley
  • 7,596
  • 5
  • 35
  • 54
  • Hey Leon ty, i am looking for in depth answer - is there any source u can refer to? I will experiment a bit on my app by trying to see when the hook gets called but i am still unclear about full context – Sergey Rudenko Sep 12 '18 at 05:43
  • The angular site contains all the info you need. https://angular.io/guide/lifecycle-hooks – Leon Radley Sep 12 '18 at 05:50
  • 1
    so as I said above - I did look through this and the docs do cover when the destruction happens for Components but the details there are quite shallow. What I want to understand is the situation with pipes, directives. services etc. When I should worry about it and when not. I am thinking now that probably to answer this question I might need to insert the lifecycle hook in all the pages and components and services and pipes and then just track what activity in the app causes destruction and then ask a question - what should be done inside the hook apart from unsubscribing. – Sergey Rudenko Sep 12 '18 at 20:09