5

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?

2
  • By "view the variable right after" you mean this.sliderRef.destroy(); console.log(this.sliderRef)? Commented Sep 13, 2018 at 16:23
  • I created this StackBlitz Demo so anyone interested can see a running code example of what the OP is referring too. Commented Sep 13, 2018 at 16:31

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

let componentRef = this.componentFactoryResolver.resolveComponentFactory(cmptName).create(this.injector);this.dynamicComponentContainer.insert(componentRef.hostView); I save componentRef in array, say, 'componentTracker' variable and we have 3 components in DOM. Can we destroy , a particular component using refrence stored in 'componentTracker' ie this.componentTracker[i].destroy();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.