更新时间:2023-12-05 18:07:52
否,如果将父组件属性分配给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);
}
}
另请参见