Can component invoke a self destroy event

自古美人都是妖i 提交于 2020-05-24 19:22:45

问题


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.

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


回答1:


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.

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);
  }
}



回答2:


Not sure about the cleanliness of such a solution, but I used:

this.viewContainerRef
    .element
    .nativeElement
    .parentElement
    .removeChild(this.viewContainerRef.element.nativeElement);



回答3:


Here is another way to do it. This works from within the component itself; no need to communicate with external components.

// imports
export class SelfDestroyableComponent implements OnInit {
    // other code

    constructor(private host: ElementRef<HTMLElement>) {}

    // whatEver function name you want to give 
    onCloseClicked() {
        this.host.nativeElement.remove();
    }

    // other code
}


来源:https://stackoverflow.com/questions/39764546/can-component-invoke-a-self-destroy-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!