加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular完全销毁动态创建的组件

发布时间:2020-12-17 17:11:51 所属栏目:安全 来源:网络整理
导读:我使用以下方法创建了许多动态组件: this.factory = this.componentFactoryResolver.resolveComponentFactory(SliderComponent);this.sliderComponentReference = viewContainerRef.createComponent(this.factory); 当我需要销毁组件时,我调用destroy方法:
我使用以下方法创建了许多动态组件:

this.factory = this.componentFactoryResolver.resolveComponentFactory(SliderComponent);
this.sliderComponentReference = viewContainerRef.createComponent(this.factory);

当我需要销毁组件时,我调用destroy方法:

this.sliderComponentReference.destroy();

我知道它从视图和实例中删除了动态组件,但是当我在注意到它仍然有信息之后立即查看变量时:

changeDetectorRef: ViewRef_ {_view: {…},_viewContainerRef: ViewContainerRef.. }
componentType:(...)
hostView: ViewRef_ {_view: {…},_viewContainerRef: ViewContainerRef... }}
injector:(...)

问题:

>如果组件实例被销毁,变量如何仍然引用它?
>组件是否仍存储在内存中?如果是这样可以检索?

解决方法

您可以在此处查看组件引用定义: https://github.com/angular/angular/blob/master/packages/core/src/view/refs.ts#L103 – 它具有changeDetectorRef,hostView等属性.当你调用.destroy时,它调用底层的viewRef.destroy方法: https://github.com/angular/angular/blob/master/packages/core/src/view/refs.ts#L277

这最终会调用其他方法,但它似乎并没有覆盖已在组件ref上定义的任何属性.据我所知,在JavaScript中,对象无法自行删除.您只能通过引用该对象来删除对象的属性.

该组件仍然存储在内存中,在某种意义上它仍然可用.但是,由于.destroy的作用,它可能无法正常工作.您可能可以重新创建它……并且还有附加方法. JavaScript执行自己的垃圾收集/内存管理,因此您无法真正强制从内存中删除这些元素.如果JavaScript在垃圾收集周期中检测到任何指针不再可以访问ref,它将释放该内存.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读