Does ViewContainerRef.clear() remove component from memory?

angular, angular-components, typescript

Solution

No, if you assign parent component property to `componentRef` angular won't remove component from memory.

Angular only destroys component and removes its own references to this component. But reference to componentRef remains to live in your component property. So i would assign `null` to it. This way garbage collect will be able to clear memory

Plunker Example (add => clear => check)

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="addComponent()">Add component</button>
      <div #container></div>
      <button (click)="clear()">Clear</button>
      <button (click)="check()">check</button>
    </div>
  `,
})
export class App {
  comp: ComponentRef<DynamicComponent>;

  constructor(
     private vcRef: ViewContainerRef, 
     private resolver: ComponentFactoryResolver) {}

  addComponent() {
    let factory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.comp = this.vcRef.createComponent(factory);
  }

  clear() {
    this.vcRef.clear();
  }

  check() {
    alert(this.comp);
  }
}

See also

- https://developer.mozilla.org/en/docs/Web/JavaScript/Memory_Management#Garbage_collection

Problem

When I create a component using `ViewContainerRef` and assign instance to a property of parent component, which is responsible for child component creation, do I need to set this property to `null` after I call `ViewContainerRef.clear()` if I want memory to be freed?

Original source