我希望能够从内部销毁我的组件。 (不是来自父级,因为它是在多个区域动态创建的)。
我从 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/