Get instance of component on active route in Angular2's router?

Viewed 5840

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).

2 Answers

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.

Related