Angular's ActivatedRoute service only exposes the type of component and the name of the outlet it relates to. However, in some cases it is necessary to get a hold of the actual instance of the component activated for a certain route.
This service lets you:
The service is intended to be managed by the PublishComponentDirective, but you can manage it yourself using the publishComponent() and unpublishComponent() methods. If you manage publication yourself, jump straight to step 3:
Import RouterXModule in your app to enable the use of the PublishComponentDirective.
Mark your outlet with publishComponent:
<router-outlet publishComponent></router-outlet>This works on named outlets as well.
RouterOutletComponentBus into your service/component and use the instance() or changes() methods.Internally, RouterOutletComponentBus keeps a map of outlet name -> component instance.
When an outlet has no name, the service uses Angular's PRIMARY_OUTLET constant as a name.
When a component is published on the service, an observable is created and is mapped with the outlet's name.
When a component is unpublished, that observable is completed and removed.
TLDR Why do I need a service?Before @bespunky/angular-zen, the common way of finding the activated component was to listen to the activated event on the relevant outlet:
<router-outlet (activate)="doSomethingWithComponent($event)"></router-outlet>This is problematic for a few reasons:
Router and ActivatedRoute give you global access to the current state. The component instance is part of that state, but is not globally accessible.