Ole
Ole

Reputation: 47038

Does a ComponentRef.destroy() method also unsubscribe the Components Event Emitters?

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?

Summary Article Incorporating Answers

https://medium.com/@ole.ersoy/subscribing-to-dynamic-component-eventemitters-4f931a5013e3

https://medium.com/@ole.ersoy/cleaning-up-subscriptions-to-dynamic-component-event-emitters-ad08c838c7a8

Upvotes: 0

Views: 858

Answers (2)

Fan Cheung
Fan Cheung

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

Sachin Shah
Sachin Shah

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

Related Questions