Angular2完全销毁当前组件 [英] Angular2 Destroy Current Component Completely
问题描述
我尝试搜索google和stackoverflow,但找不到答案.所以我的问题很简单:我如何去除角度2、4中的当前分量"
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"
示例:
<div (click)="remove($event)">Remove Current Component</div>
remove($event) {
// this.destroy() ????
}
基本上我想要的是ComponentRef
,请参见此答案 ngOnDestroy()
,其中调用this.cmpRef.destroy()
:
Basically what i want is ComponentRef
see this answer ngOnDestroy()
which calls this.cmpRef.destroy()
:
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
但是由于动态创建组件,他得到了ComponentRef
.
But he is getting the ComponentRef
due to dynamically creating the component.
推荐答案
您可以在父模板中的component元素上使用*ngIf="myBoolean"
指令.当myBoolean
变为false
时,该组件将被破坏.
You can use a *ngIf="myBoolean"
directive on the component element in the parent template. When myBoolean
becomes false
, the component will be destroyed.
没有更多的组件或DOM元素. (并引发了ngOnDestroy
事件)
No more component or DOM element present. (and ngOnDestroy
event raised)
如果myBoolean
再次变为true
,则将实例化一个新组件.
If myBoolean
becomes true
again, a new component will be instantiated.
一个新的将出现在DOM中(并引发ngOnInit
事件)
A new one will appear in DOM (and ngOnInit
event raised)
您的click事件可以发出一个事件(与(myEventEmitter)语法绑定在父级中,然后父级组件中的方法 可以将布尔值设置为false
.
Your click event can emit an event (binded in the parent with the (myEventEmitter) syntax, and a method in the parent component can then just set the boolean to 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
这篇关于Angular2完全销毁当前组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!