Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Destroying a dynamically created component completely

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:

  1. How come the variable still has reference to the component instance if it was destroyed?

  2. Is the component still stored in memory? If so is it retrievable?

like image 864
L1ghtk3ira Avatar asked Nov 08 '22 02:11

L1ghtk3ira


1 Answers

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.

like image 111
Explosion Pills Avatar answered Nov 11 '22 11:11

Explosion Pills