如何使用ComponentRef从内部销毁我的Component?

Jon*_*002 8 angular

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

我从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()
    }
}
Run Code Online (Sandbox Code Playgroud)

ale*_*ano -1

当您从另一个组件(父组件)实例化该组件时,这非常有用。

您可以尝试从组件 obejct 调用 ngOnDestroy() this.ngOnDestroy()

如果您正在开发的 Angular 版本不允许您这样做,并且由于您想从同一个组件中销毁它,您需要要求父级使用输出和/或发射器来完成此操作。