[英]Is there any way to unsubscribe child component's Subscriptions when element is removing from DOM using `renderer2.removeChild()` in angular?
Rendering HelloComponent in AppComponent and when the element is removed from DOM by using renderer.removeChild()
, HelloComponent
's ngOnDestroy
method is not firing.在AppComponent 中渲染HelloComponent并且当使用
renderer.removeChild()
从 DOM 中删除元素时,不会触发HelloComponent
的ngOnDestroy
方法。 So unable to close the subscriptions of Hello Component.所以无法关闭Hello组件的订阅。
Wow, don't you want to destroy them with plain old *ngIf?哇,你不想用简单的旧 *ngIf 摧毁它们吗? It would make life so much easier.
它会让生活变得更加轻松。 Anyway, you can use mutation observers.
无论如何,您可以使用突变观察者。
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver 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 Stackblitz 在这里: https ://stackblitz.com/edit/angular-wutq9j ? file = src/app/hello.component.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.