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

标签 angular typescript angular-components

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

最佳答案

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

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

Plunker Example (添加 => 清除 => 检查)

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

另见

关于angular - ViewContainerRef.clear() 是否从内存中删除组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43680712/

相关文章:

angular - Ionic 4 自定义环境文件

html - ngFor 循环中的换行符

javascript/Angular : add 'line break' via string

javascript - 系统 JS 不加载模块

javascript - 如何将一些过滤器与恢复初始对象一起使用?

angular - 在 angular4 中发布数据时是否发生缺少参数 : email, 密码错误?

angular - 删除行后无法刷新 p 表中的数据 (PrimeNg)

typescript - 联合函数类型的可赋值性规则

angular - 使用 angular2 中的组件交互通过 <router-outlet> 传递数据

angular - 从 Angular 4 中的其他组件切换侧边栏菜单