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

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

问题描述

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

解决方案

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

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

Plunker 示例(添加 => 清除 =>检查)

@Component({选择器:'我的应用',模板:`<div><button (click)="addComponent()">添加组件</button><div #container></div><button (click)="clear()">Clear</button><button (click)="check()">check</button>

`,})出口类应用{comp: ComponentRef;构造函数(私有 vcRef: ViewContainerRef,私有解析器:ComponentFactoryResolver) {}添加组件(){让工厂 = this.resolver.resolveComponentFactory(DynamicComponent);this.comp = this.vcRef.createComponent(工厂);}清除() {this.vcRef.clear();}查看() {警报(this.comp);}}

另见

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?

解决方案

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

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

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