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
To force a component to be destroyed, you use the HostListener from the Angular Core library. When using HostListener , you specify the event you want to listen to on the host of the component. In our case, we listen for the unloaded event so that when the page is unloaded, ngOnDestroy() will be triggered.
1 suggested answer @Padrezz you just need to remove the component out of the rendered html and it will be automatically destroyed. To do this you would just use a blade @if conditional, to conditionally render the child component. Setting the condition to false, would then remove the component from the page.
ngOnDestroy() gets called when a component is about to be destroyed. Notice how the example "destroys" the child component via the conditional ngIf='showChild'. By toggling the value of showChild, Angular creates and destroys the child component each time this value changes.
because you want to unload the component, not merely hide it. export class ImageModalComponent implements OnInit { @Output() close = new EventEmitter(); public hideModal() { this. close. emit(); // here we tell the parent that the "close" button has been clicked. } }
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); } }
Not sure about the cleanliness of such a solution, but I used:
this.viewContainerRef .element .nativeElement .parentElement .removeChild(this.viewContainerRef.element.nativeElement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With