当我使用 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/