Angular controller references instances exists after ngDestroy

Viewed 66

Please have a look on following StackBlitz example. Please open Dev tools and have a look on console output while switching back and forth between login & home links. Each toggle will add instance of HomeViewComponent to out development array.

Small code tour for those, who don't like to go through it on their own:

App component code handles routing of app. There are singe router outlet that will load one of two views. Enabling view A forces view B to be pushed via ngOnDestroy lifecycle hook. There are no pending subscriptions in any of components, no child references, no implicit or explicit references to components, no nothing. In other words, after ngOnDestory, component can be safely discarded.

It turns out, that old component references are not discarded anyhow, remains stuck by Angular.

Same behavior would be achieved if:

  • References would be stored inside some service array
  • No reference would be stores, but memory footprint would be browsed in dev Tools

The question is:

  • Why angular seems not to care about old components, that shall be scrapped?
  • How this can be explicitly requested by app developer?

Disclaimer

This topic was already discussed on Angular bug tracking github forum. The dev team claims were clear: this will not happen when in production mode. If you examine main.ts file, you might see, this behavior still occurs. Beside this, we got real-life examples of production apps that accumulates dead components over time.

I'm adding JavaScript tag, because this might be related in some V8/any other JS engine implementation.

This issue and example was generously provided by JoshThunar, many thanks for support.

1 Answers

If you store references to a component, the component will still be removed from dom, but the class itself will not be able to be garbage collected by JS because there are still references to the actual component.

Angular itself is not involved with garbage collection, but it will ensure that there are no references to the component after it has been destroyed.

Related