Wow, don’t you want to destroy them with plain old *ngIf? It would make life so much easier. Anyway, you can use mutation observers.
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Roughly, and crudely, it could look like this:
constructor(private ref: ElementRef) {}
ngOnInit() {
const ref = this.ref;
this.subscription = this.myObservable.subscribe(data => {
console.log(data);
});
const config = { childList: true };
const cb = function(mutationList, observer) {
for (const mutation of mutationList) {
for (const node of mutation.removedNodes) {
if(node === ref.nativeElement) {
console.log("I've just been destroyed");
}
}
}
};
const observer = new MutationObserver(cb);
observer.observe(this.ref.nativeElement.parentNode, config);
}
Stackblitz here:
https://stackblitz.com/edit/angular-wutq9j?file=src/app/hello.component.ts