I create a lot of dynamic components using:
this.factory = this.componentFactoryResolver.resolveComponentFactory(SliderComponent);
this.sliderComponentReference = viewContainerRef.createComponent(this.factory);
When I need the component destroyed I call the destroy method:
this.sliderComponentReference.destroy();
I understand that it deleted the dynamic component from the view and it's instance however when I view the variable right after I notice it still has information:
changeDetectorRef: ViewRef_ {_view: {…}, _viewContainerRef: ViewContainerRef.. }
componentType:(...)
hostView: ViewRef_ {_view: {…}, _viewContainerRef: ViewContainerRef... }}
injector:(...)
Questions:
How come the variable still has reference to the component instance if it was destroyed?
Is the component still stored in memory? If so is it retrievable?
You can see the component ref definition here: https://github.com/angular/angular/blob/master/packages/core/src/view/refs.ts#L103 -- it has the changeDetectorRef
, hostView
, etc. properties. When you call .destroy
, it calls the underlying viewRef.destroy
method: https://github.com/angular/angular/blob/master/packages/core/src/view/refs.ts#L277
This ends up calling other methods, but it doesn't seem to actually overwrite any of the properties that were already defined on the component ref. As far as I know in JavaScript, an object can't delete itself. You can only delete properties of an object with a reference to that object.
The component is still stored in memory and it is still usable in some sense. However, it may not work as you expect because of what .destroy
does. You might be able to recreate it though ... and there are attach
methods as well. JavaScript does its own garbage collection / memory management, so you can't really force these elements to be removed from memory. If JavaScript detects that the ref is no longer accessible by any pointers during a garbage collection cycle, it will free that memory.
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