【问题标题】:how to use destroy() method of class ComponentRef<C>如何使用 ComponentRef<C> 类的 destroy() 方法
【发布时间】:2018-01-10 11:37:10
【问题描述】:

我正在尝试使用 ComponentRef 类 将组件作为 private compRef : ComponentRef

注入构造函数来销毁组件

它给出 Error: Uncaught (in promise): Error: No provider for ComponentRef!

尝试在组件级别和 app.module 的提供程序数组中包含 ComponentRef,但它说类型 ComponentRef 不能分配给类型“Providers”。

关于如何实现 ComponentRef 以便能够使用 destroy() 方法的任何帮助?

谢谢。

【问题讨论】:

  • 请参阅my answer 了解销毁方法的说明。为什么要销毁组件?
  • @maximus,感谢您的帮助。我需要清除与该组件相关的所有属性和对象。我认为 destroy() 方法是一种快速而干净的方法。
  • 我明白了。 destroy 实际上并没有按照您的想法做。检查我的更新答案
  • 太好了,感谢您的澄清。

标签: angular


【解决方案1】:

destroy() 方法可以在动态创建的组件上调用。这是一个简单的例子:

export class SampleComponent implements AfterViewInit {
    @ViewChild("vc", {read: ViewContainerRef}) vc: ViewContainerRef;

    constructor(private resolver: ComponentFactoryResolver) {}

    ngAfterViewInit() {
        const componentFactory = this.resolver.resolveComponentFactory(BComponent)
        const componentRef = this.vc.createComponent(componentFactory);
        componentRef.destroy(); <-------------------
    }
}

如果不是动态创建的,您无法访问组件的componentRef

我需要清除与之相关的所有属性和对象 组件。

destroy 方法实际上并没有清除组件实例上的任何属性。它只是从视图容器或applicationRef 中分离视图,分离投影视图并更新视图组件的状态。它还会在执行相同操作集的子组件和嵌入视图上触发destroy

阅读这些文章了解更多信息:

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 2016-11-03
    • 2012-11-06
    • 1970-01-01
    • 2012-11-18
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多