Angular 2-销毁子组件 [英] Angular 2 - destroy child component
问题描述
我从Angular 2开始,我已经初始化了一个子组件"ChildCmp",在我需要通过单击来销毁该组件之后,说:
I am starting with Angular 2, I have a child component "ChildCmp" initialized and after I need destroy component through a click, let say:
@Component({
selector: 'main-cmp',
templateUrl: './main-cmp.html',
directives: [ChildCmp]
})
class MainCmp {
@ViewChild(ChildCmp)
childCmp: ChildCmp;
destroyChildClick(){
this.childCmp.destroy();
}
}
但先前的代码无法运行,destroy()未定义,异常为:
but the previous code doesn't run, destroy() is undefined and exception is:
TypeError:this.childCmp.destroy不是函数
TypeError: this.childCmp.destroy is not a function
我已阅读此线程,并在那里正在使用 ViewContainerRef.createComponent(),由此创建的组件是"ComponentRef" 的实例,但是childCmp没有实现"ComponentRef".
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.
我如何实现或注入destroy方法?
How I can implement or inject the destroy method?
谢谢大家!
推荐答案
尝试一下
export class MainCmp {
@ViewChild(ChildCmp) childRef: ChildCmp;
destroyClick() {
if (this.childRef) {
this.childRef.destroy();
}
}
}
这篇关于Angular 2-销毁子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!