gpt4 book ai didi

angular - 如何使用 ComponentRef 从内部销毁我的组件?

转载 作者:行者123 更新时间:2023-12-04 11:11:55 26 4
gpt4 key购买 nike

我希望能够从内部销毁我的组件。 (不是来自父级,因为它是在多个区域动态创建的)。

我从 angular 的 api 中读到他们有一个 ComponentRef 对象。我试过将它包含在构造函数中,但它说它需要一个参数,我不确定要传递给它什么。

链接:https://angular.io/api/core/ComponentRef

如何在我的组件中使用 ComponentRef 来销毁它?

import { Component, ComponentRef, OnInit } '@angular/core';
export class MyComponent implements OnInit {
constructor(private ref: ComponentRef) {}

ngOnInit() {
this.ref.destroy()
}
}

最佳答案

当您从另一个组件(父组件)实例化组件时,这很有用。
您可以尝试从组件对象中调用 ngOnDestroy() this.ngOnDestroy() .
如果您正在使用的 Angular 版本不允许您使用,并且由于您想从同一个组件中销毁它,您需要要求父级使用输出和/或发射器来完成它。

关于angular - 如何使用 ComponentRef 从内部销毁我的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45757822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com