ViewContainerRef.clear()是否从内存中删除组件?

Leo*_*Bor 4 typescript angular-components angular

当我创建一个组件ViewContainerRef并将实例分配给父组件的属性(负责子组件创建)时,如果我想要释放内存,nullViewContainerRef.clear()是否需要在调用之后将此属性设置为?

yur*_*zui 8

不,如果将父组件属性指定给componentRefangular,则不会从内存中删除组件.

Angular仅销毁组件并删除其对此组件的引用.但是对componentRef的引用仍然存在于组件属性中.所以我会分配null给它.这样垃圾收集就能清除内存

Plunker示例(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);
  }
}
Run Code Online (Sandbox Code Playgroud)

也可以看看