ViewContainerRef.clear()是否从内存中删除组件? [英] Does ViewContainerRef.clear() remove component from memory?

查看:206
本文介绍了ViewContainerRef.clear()是否从内存中删除组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

Angular仅销毁组件,并删除其对此组件的引用.但是对componentRef的引用仍然存在于您的component属性中.因此,我将为其分配null.这样垃圾收集将能够清除内存

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

另请参见

这篇关于ViewContainerRef.clear()是否从内存中删除组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆