组件可以调用自毁事件吗 [英] Can component invoke a self destroy event
问题描述
我有一个父组件,单击链接后会打开一个新组件,这个新组件应该有一个关闭按钮,当关闭时,该按钮会向父母发送一个关闭消息并销毁自身.
I have a parent component which opens a new component on click of a link, this new component is supposed to have a close button which on close sends a closing message to parent and destroy itself.
我们可以使用ngOnDestroy
方法发送关闭消息,但是如何调用子组件的销毁.
We can send the closing message using ngOnDestroy
method, but how do I invoke the destroying of the child component.
<parent>
<child></child> //child to be opened on click but close
//event should be inside the child componenet
</parent>
如果我在这里遇到一些概念上的错误,请纠正我.谢谢
Do correct me if i am having some conceptual mistake here. Thanks
推荐答案
如果您使用ViewContainerRef.createComponent()
添加组件,如
If you add a component using ViewContainerRef.createComponent()
like shown in Angular 2 dynamic tabs with user-click chosen components, then the component can destroy itself when you pass cmpRef
to the created component.
否则,我认为没有办法.您可以将值传递给父级,以便*ngIf
删除该组件.
Otherwise I don't think there is a way. You can pass a value to the parent so that an *ngIf
removes the component.
<child *ngIf="showChild" (close)="showChild = false"></child>
class ParentComponent {
showChild:boolean = true;
}
class ChildComponent {
@Output() close = new EventEmitter();
onClose() {
this.close.emit(null);
}
}
这篇关于组件可以调用自毁事件吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!