Dimitri Lozovoy
Dimitri Lozovoy

Reputation: 453

Angular2: Link from one child to another, on the same level

I have a parent component A and a child component B, with A referring to B like this:

@RouteConfig([
{
  path: '/screen-b/...',
  name: 'ScreenB',
  component: ScreenBComponent
}
])

B has a router outlet and three sub-components, defined like this:

@RouteConfig([
  {
    path: '/screen-aa',
    name: 'ScreenAA',
    component: ScreenAAComponent,
    useAsDefault: true
  },
  {
    path: '/screen-bb',
    name: 'ScreenBB',
    component: ScreenBBComponent
  },
  {
    path: '/screen-cc',
    name: 'ScreenCC',
    component: ScreenCComponent
  }
])

When inside component B's template, I put in links like this, the sub-components AA, BB and CC show up just fine in the router outlet of B:

<a [routerLink]="['ScreenAA']">Screen AA</a>
<a [routerLink]="['ScreenBB']">Screen BB</a>
<a [routerLink]="['ScreenCC']">Screen CC</a>

However, when I put the same link inside AA, BB or CC, to link to one another, nothing happens (the URL in the address bar does change, though). I am guessing that this is because AA, BB, CC do not have router outlets themselves, and this is where Angular2 would want to put them.

It seems that it is only possible to route down the hierarchy, and always only in a lower-level router outlet, but never to the same level, or above. How to achieve this functionality that is so essential for most websites?

All I need is to be able to click inside a component and then have that component be replaced with something else, not open up something in a lower-level router outlet.

Upvotes: 2

Views: 1611

Answers (2)

Dimitri Lozovoy
Dimitri Lozovoy

Reputation: 453

Removed the following from the page I was trying to link from:

directives: [RouterOutlet, ROUTER_DIRECTIVES],
providers: [
ROUTER_PROVIDERS,
]

And the links started working.

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86750

You have to put router-outlet in every component where you want to load some contents via routing, secondly i think you have to use your code like this to make things work.

<a [routerLink]="['../ScreenAA']">Screen AA</a>
<a [routerLink]="['../ScreenBB']">Screen BB</a>
<a [routerLink]="['../ScreenCC']">Screen CC</a>

because according to your question your components B is having an child components and for those chil components B component is now parent so by prepending url with ../ so ,if the route begins with ../ the router will look at the current component's parent.

from angular's official

The first route name should be prepended with /, ./, or ../. If the route begins with /, the router will look up the route from the root of the app. If the route begins with ./, the router will instead look in the current component's children for the route. And if the route begins with ../, the router will look at the current component's parent.

Upvotes: 4

Related Questions