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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.