typescript - Angular 2 - 销毁子组件

标签 typescript angular

我从 Angular 2 开始,我有一个子组件“ChildCmp”已初始化,在我需要通过单击销毁组件后,假设:

@Component({
selector: 'main-cmp',
templateUrl: './main-cmp.html',
directives: [ChildCmp]
})
class MainCmp {
    @ViewChild(ChildCmp)
    childCmp: ChildCmp;
    destroyChildClick(){
        this.childCmp.destroy();
    }
}

但是前面的代码没有运行,destroy() 是未定义的,异常是:

TypeError: this.childCmp.destroy is not a function

我已阅读 this thread并且有使用 ViewContainerRef.createComponent(),用它创建的组件是 “ComponentRef” 的实例,但是 childCmp 没有“ComponentRef”实现。

如何实现或注入(inject) destroy 方法?

谢谢大家!

最佳答案

简答

export class MainCmp {

   @ViewChild(ChildCmp) childRef: ChildCmp;

   destroyClick() {
      this.childRef?.destroy();
   }
}

我知道上面的代码在正常情况下没有意义,我不会使用它,但由于我没有上下文,我根据给定的问题进行了回答。 parent 应该先检查 child 引用是否被定义,然后它可以销毁 child 。

更好的方法是使用 NgIf 来销毁子组件,但同样我不知道上下文或用例。

@Component({
  selector: 'main-cmp',
  template: `
    <child-cmp *ngIf="childDestroyed"></child-cmp>
    <button (click)="childDestroyed = true">Destroy child</button>
  `,
})
class MainCmp {
  childDestroyed: boolean;
}

关于typescript - Angular 2 - 销毁子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676997/

相关文章:

node.js - 使用 tsyringe 使用 Typescript 进行动态依赖注入(inject)

typescript - REST - 强类型模型

angular - 使用 Angular 4 中另一个的响应调用另一个可观察对象

javascript - 从顶级组件中的延迟加载路由获取自定义路由数据

angular - ionic 警报强制输入

angular - 如何在不创建新指令的情况下向模板驱动表单添加自定义验证(最大字符数)

javascript - Node.js + Typescript + Webpack = 找不到模块

javascript - Angular 5 接口(interface)变量无法分配给类型问题

angular - 无法在 VS 代码中调试 dockerize Angular 应用程序 - 无法连接到目标 : socket hang up

Angular2 - 如何延迟初始加载直到服务完成?