9

I know that ActivatedRouteSnapshot.component in Angular2 contains the reference/class to the activated route if I call Router.routerState.snapshot but how to get for the component class the current (or minimal: one created) instance for it?

Injector.get(..) does not return instances of components and creating a new instance of a component does also not help (me).

GreNodge
  • 767
  • 1
  • 10
  • 25
  • 1
    can you elaborate a bit what you're doing? where do you want to get the reference to the component class? what component? – Max Koretskyi Aug 01 '17 at 07:42
  • The component has (depending on the environment) sometimes a property (`showFooter`) set to `true` and sometimes to `false` - it depends on the data it receives from a REST endpoint. If it is false the App component which contains the `` and also the `` should hide or show the footer. – GreNodge Aug 01 '17 at 07:51

2 Answers2

17

You can use

<router-outlet
  (activate)='onActivate($event)'
  (deactivate)='onDeactivate($event)'></router-outlet>

where $event is the component instance and for example assign it to a service to make it available globally.

See also https://angular.io/api/router/RouterOutlet

You can also create a custom <router-outlet> component that does that automatically.

Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
1

You should be able to get it with the ActivateRoute.

For example, if you have the Injector service:

const activatedRoute: ActivateRoute = this.injector.get(ActivatedRoute);

then

component reference: this.injector.get(activatedRoute.component);

However, this only works if the injector instance you use has reference to that component itself.

In my example, this can be used to find the ViewComponent from a child of that view.

|- ViewComponent
  |- ChildComponent
    |- ChildComponent
      ... injector here -> using the code above, gets the ViewComponent' instance 
  |- ChildComponent

This may not work in your instance, however, hopefully this may help someone.

Jmsdb
  • 505
  • 3
  • 9