1

Let's say we have ComponentA with that template:

 <div>
       <router-outlet></router-outlet>
 </div>

ComponentA has routeConfig to route to ComponentB.

How to get ComponentA from the routed componentB?

I tried to inject @Host to ComponentB but I get an exception.

almog
  • 798
  • 1
  • 7
  • 18

1 Answers1

2

The router adds components using DynamicComponentLoader. Such components have limited capabilities (no @Input() can be passed, @Host() can't be used).

You can use a shared service where ComponentA passes itself in and ComponentB can read the value.

A similar use case is explained here Update parent component title from routed child component in Angular 2. The service doesn't have to be global. It can also be only shared between the parent and the child by adding it to providers: [MySharedService] of ComponentA instead of bootstrap() as shown in the linked answer.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Do you recommend to extend the RouterOutlet and manage a routing map to keep track of the routing changes? I found it very difficult to know what is the components tree that was routed . – almog Mar 31 '16 at 12:32
  • Extending `RouterOutlet` seems to be common practice, I haven't done it myself yet. Another way is to create a shared service, inject the `constructor(router:Router)` and subscribe to `router.subscribe(...)` to get notified about route changes. – Günter Zöchbauer Mar 31 '16 at 12:41