JackM
JackM

Reputation: 284

Use RouterLink from a nested component

Using Angular 2 beta.0

I have a component structure like so

App (Has RouteConfig)
 -> List 
 | -> ListItem (Want to use RouterLink from here)

This results in an error: Component "List" has no route config.

So I put a RouteConfig on the List component like so...

@RouteConfig([
  {path: '/:id', name: 'Details', component: Detail}
])

But I get an error in angular like Error: Child routes are not allowed for "/list". Use "..." on the parent's route path.

I have tried adding these 3 dots before and after the /list path in that route config... with no success.

The documentation on router is very light and though I know this is supposed to be based off of ui-router, I'm not seeing the parallel to add nested routes

Upvotes: 8

Views: 10433

Answers (2)

hesparza
hesparza

Reputation: 181

If what you are trying to do is to use the routerLink from one child component to actually go to one of your parent's configured routes, then you don't need to put any RouterConfig on the child, you just need to make sure that the route is configured correctly in your parent and then add the ROUTER_DIRECTIVES constant in your child's directives property inside the child's decorator.

It will be something like this:

Parent:

import { ROUTER_PROVIDERS, RouteConfig, ROUTER_DIRECTIVES } from 'angular2/router';
        :
    (some more imports)
        :
@Component({
        :
    directives: [ROUTER_DIRECTIVES],
    providers: [ROUTER_PROVIDERS],
        :
})

@RouteConfig([
  {path: '/:id', name: 'Details', component: Detail}
])

Child:

import { ROUTER_DIRECTIVES } from 'angular2/router';
    :
    :
@Component({
    :
    directives: [ROUTER_DIRECTIVES],
    :
})

Also, don't forget to configure your routerLink correctly by providing the route you want to send the user to as the first parameter of the array and then add the parameters you want to send to the target route by using the same name you gave them in the RouteConfig, like this:

<a [routerLink]="['Details', { id: product.productId }]"> Details link </a>

Upvotes: 0

Aico Klein Ovink
Aico Klein Ovink

Reputation: 1647

You can use it like this, in parent component:

@RouteConfig([
  {path: '/', component: HomeComponent, as: 'Home'},
  {path: '/list/...', component: ListComponent, as: 'List'}
])

And then in your ListComponent, define your child routes:

@RouteConfig([
  { path: '/:id', component: ListItem, as: 'ListItem' }
])

Make sure the ListComponent has a <router-outlet></router-outlet> as well..

Upvotes: 20

Related Questions