Javascript Angular2 彻底销毁当前组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45855673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 Destroy Current Component Completely
提问by Touqeer Shafi
I tried searching google and stackoverflow but could not find an answer. So my question is simple "How can i remove current component in angular 2, 4"
我尝试搜索 google 和 stackoverflow,但找不到答案。所以我的问题很简单“我如何删除角度 2、4 中的当前组件”
example:
例子:
<div (click)="remove($event)">Remove Current Component</div>
remove($event) {
// this.destroy() ????
}
Basically what i want is ComponentRefsee this answerngOnDestroy()which calls this.cmpRef.destroy():
基本上我想要的是ComponentRef看到这个调用的答案:ngOnDestroy()this.cmpRef.destroy()
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
But he is getting the ComponentRefdue to dynamically creating the component.
但是他得到了ComponentRef动态创建组件的原因。
回答by Pac0
You can use a *ngIf="myBoolean"directive on the component element in the parent template. When myBooleanbecomes false, the component will be destroyed.
您可以*ngIf="myBoolean"在父模板中的组件元素上使用指令。当myBoolean变成 时false,组件将被销毁。
No more component or DOM element present. (and ngOnDestroyevent raised)
不再存在组件或 DOM 元素。(和ngOnDestroy事件引发)
If myBooleanbecomes trueagain, a new component will be instantiated.
如果再次myBoolean变为true,将实例化一个新组件。
A new one will appear in DOM (and ngOnInitevent raised)
一个新的将出现在 DOM 中(并ngOnInit引发事件)
Your click event can emit an event (binded in the parent with the (myEventEmitter) syntax, and a method in the parent componentcan then just set the boolean to false.
您的点击事件可以发出一个事件(使用 (myEventEmitter) 语法绑定在父组件中,然后父组件中的方法可以将布尔值设置为false.
Demonstration on this Plunker. If it doesn't suit your need, consider editing your question to provide more specific details, including a Minimal Complete Verifiable example
这个Plunker的演示。如果它不适合您的需要,请考虑编辑您的问题以提供更具体的详细信息,包括最小完整可验证示例

