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

前端之家收集整理的这篇文章主要介绍了angular – ViewContainerRef.clear()是否从内存中删除组件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我使用ViewContainerRef创建一个组件并将实例分配给负责子组件创建的父组件的属性时,如果我想要释放内存,我是否需要在调用ViewContainerRef.clear()之后将此属性设置为null?

解决方法

不,如果您将父组件属性分配给componentRef angular将不会从内存中删除组件.

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

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);
  }
}

也可以看看

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

猜你在找的Angularjs相关文章