angular – ViewContainerRef.clear()是否从内存中删除组件?
发布时间:2020-12-17 17:23:13 所属栏目:安全 来源:网络整理
导读:当我使用ViewContainerRef创建一个组件并将实例分配给负责子组件创建的父组件的属性时,如果我想要释放内存,我是否需要在调用ViewContainerRef.clear()之后将此属性设置为null? 解决方法 不,如果您将父组件属性分配给componentRef angular将不会从内存中删除
当我使用ViewContainerRef创建一个组件并将实例分配给负责子组件创建的父组件的属性时,如果我想要释放内存,我是否需要在调用ViewContainerRef.clear()之后将此属性设置为null?
解决方法
不,如果您将父组件属性分配给componentRef angular将不会从内存中删除组件.
Angular仅销毁组件并删除其对此组件的引用.但是对componentRef的引用仍然存在于组件属性中.所以我会为它分配null.这样垃圾收集就能清除内存 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); } } 也可以看看 > https://developer.mozilla.org/en/docs/Web/JavaScript/Memory_Management#Garbage_collection (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |