I want to be able to destroy my component from within itself. (Not from parent since it's dynamically created in multiple areas).
I've read from angular's api that they have a ComponentRef object. I've tried including it in the constructor but it says it needs an argument and I'm not sure what to pass to it.
Link: https://angular.io/api/core/ComponentRef
How can use ComponentRef in my component to destroy it?
import { Component, ComponentRef, OnInit } '@angular/core';
export class MyComponent implements OnInit {
constructor(private ref: ComponentRef) {}
ngOnInit() {
this.ref.destroy()
}
}
you can do it like this:
export class SelfDestroyableComponent implements OnInit {
constructor(private host: ElementRef<HTMLElement>) {}
// whatEver function name you want to give
selfDestroy() {
this.host.nativeElement.remove();
}
}
and call selfDestroy method whenever you want to destroy component
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