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

◇◆丶佛笑我妖孽 提交于 2020-02-20 08:48:29

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/45431682/get-instance-of-component-on-active-route-in-angular2s-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!