简体   繁体   English

Angular 2 - 破坏子组件

[英]Angular 2 - destroy child component

I am starting with Angular 2, I have a child component "ChildCmp" initialized and after I need destroy component through a click, let say: 我从Angular 2开始,我有一个子组件“ChildCmp”初始化,在我需要通过点击销毁组件后,让我们说:

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

but the previous code doesn't run, destroy() is undefined and exception is: 但是前面的代码没有运行,destroy()是未定义的,异常是:

TypeError: this.childCmp.destroy is not a function TypeError:this.childCmp.destroy不是函数

I have read this thread and there are using ViewContainerRef.createComponent() , the component created with this is an instance of "ComponentRef" , but the childCmp doesn't have "ComponentRef" implementation. 我已经阅读了这个线程 ,并且使用了ViewContainerRef.createComponent() ,使用它创建的组件是“ComponentRef”的实例,但是childCmp没有“ComponentRef”实现。

How I can implement or inject the destroy method? 我如何实现或注入destroy方法?

Thanks for all! 谢谢大家!

Try this 试试这个

export class MainCmp {

   @ViewChild(ChildCmp) childRef: ChildCmp;

   destroyClick() {

      if (this.childRef) {
         this.childRef.destroy();
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM