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

标签 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()
    }
}

最佳答案

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

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

相关文章:

angular - ?如何向Angular2项目添加新的路由依赖

javascript - Angular 单元测试授权 header 拦截器不起作用

javascript - 使用带有 angular2 的所见即所得编辑器文本

Angular 子类模板访问父类(super class)中定义的变量

php - 如何在单个字段 laravel 中存储多个值

angular - 如果用户已经在 Angular 4 中登录,如何限制对登录路由的访问?

javascript - Angular2 Http 请求

node.js - 没有服务器的 Angular 2 应用程序?

typescript - 使用 systemjs 在 typescript 中的 Angular 2 应用程序中导入位于应用程序文件夹之外的共享服务

angular - ag-grid cellrenderer : adding html tags to cells but not in the template but as return values of a function