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"
example:
<div (click)="remove($event)">Remove Current Component</div>
remove($event) {
// this.destroy() ????
}
Basically what i want is ComponentRef
see this answer ngOnDestroy()
which calls this.cmpRef.destroy()
:
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
But he is getting the ComponentRef
due to dynamically creating the component.
So, basically Router in Angular 2 destroys inactive components (my tabs!).
Forcing a Component to Destroy Itself. To make a component destroy itself when the user navigates away from it, you have to make the component call its ngOnDestroy() lifecycle hook when the page unloads. This is done by leveraging the host page's life cycle.
In our dynamic component loader, it will be load component using createComponent() of ViewContainerRef. The ComponentRef of the newly created component and call the clear() method of ViewContainerRef destroys the existing view in the container.
child components from parent can be destroyed using reference of child component in parent component. this. dataArray = []; this.
You can use a *ngIf="myBoolean"
directive on the component element in the parent template. When myBoolean
becomes false
, the component will be destroyed.
No more component or DOM element present. (and ngOnDestroy
event raised)
If myBoolean
becomes true
again, a new component will be instantiated.
A new one will appear in DOM (and ngOnInit
event raised)
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
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