Search code examples
angularangular2-routingrouter-outlet

Navigate to top level route in named router from nested components


I have a layout like this:

<div>
  <router-outlet />
  
  <div class="details">
    <router-outlet name="details"></router-outlet>
  </div>

</div>

In routes, at the top level, I have:

routes = [
  {
    path: 'some-component',
    component: SomeComponent,
  },
  {
    path: 'my-details',
    component: DetailsComponent,
    outlet: 'details'
  }
]

Now, when I navigate to "some-component" route I have a [routerLink] in its template. I want that router link to trigger the "my-details" route within the details router outlet.

I have:

[routerLink]="[{outlets:{details:['my-details']}}]"

but clicking on it doesn't pick up the route. It says not found (I have a route to pickup all routes not matched).

Seems like components rendered within the primary router outlet cannot trigger the route in the named router when it is at the same level as the primary router. I've tried putting [relativeTo]="route.parent" into routerLink but it is still not working.

What am I missing?

PS. If I put the named router into SomeComponent and make the named route a child of the main route, then it works. But that's not what I want.


Solution

  • Believe that the problem is you don't provide the first value with the path in the [routerLink] array, by default it will use the current route. So it render the <a> element as:

    <a href="<Domain URL>/some-component/some-component(details:my-details)></a>
    

    As your "my-details" route is not a child route for "some-components", this will fail to match any route.

    You should provide an empty string or "/" in the first value of the array for [routerLink].

    <a [routerLink]="['', {outlets:{details:['my-details']}}]">Details</a>
    

    This will render the <a> element as:

    <a href="<Domain URL>/some-component(details:my-details)></a>
    

    I believe with [relativeTo] also works as well:

    <a [routerLink]="[{outlets:{details:['my-details']}}]" 
      [relativeTo]="route.parent">Details</a>
    

    Demo @ StackBlitz