Reputation: 47038
If we have a dynamic (Created dynamically - not declaratively) ComponentRef
instance, and we call destroy()
on the instance, will that unsubcribe any subscriptions to EventEmitter
instances that are subscribed to.
For example if we an output
EventEmitter
and we subscribe to it like this:
this.componentRef.instance.output.subscribe(event => console.log(event));
And we call componentRef.destroy()
will that take care of unsubscribing the subscription to the output
EventEmitter
?
https://medium.com/@ole.ersoy/subscribing-to-dynamic-component-eventemitters-4f931a5013e3
Upvotes: 0
Views: 858
Reputation: 11345
There's a onDestroy
callback from componentRef that you can hook to clean up the subscriptions
/**
* A lifecycle hook that provides additional developer-defined cleanup
* functionality for the component.
* @param callback A handler function that cleans up developer-defined data
* associated with this component. Called when the `destroy()` method is invoked.
*/
abstract onDestroy(callback: Function): void;
example
const sub=this.componentRef.instance.output.subscribe(event => console.log(event));
this.componentRef.onDestroy(()=>{
sub.unsubscribe()
})
Upvotes: 1
Reputation: 4533
When subscribe method is called there is a subscription object returned. If I keep track of that object. You have to can call unsubscribe whenever Angular is destroying the component.
E.x:
ngOnDestroy() {
this.sub.unsubscribe();
}
It will not unsubscribe from ngOnDestroy()
Upvotes: 1