Can component invoke a self destroy event
Not sure about the cleanliness of such a solution, but I used:
this.viewContainerRef
.element
.nativeElement
.parentElement
.removeChild(this.viewContainerRef.element.nativeElement);
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
}
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);
}
}