组件可以调用自毁事件吗 [英] Can component invoke a self destroy event

查看:58
本文介绍了组件可以调用自毁事件吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父组件,单击链接后会打开一个新组件,这个新组件应该有一个关闭按钮,当关闭时,该按钮会向父母发送一个关闭消息并销毁自身.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆