1

I'm trying to navigate to a page using a routerLink after getting an id, which I can get.

The problem is the link is showing up as '/page;id=10/component'. I would like for it to show as '/page/10/component' (not matrix notation - no ';id=' )

In my app.routes.ts:

@RouterConfig = [
    { path: 'page/:id/component', component: MyComponent, data: {id: 'item.id'} }
];

In my page:

<a [routerLink]="['page', {id: item.id}, 'component']">

I'm using the latest Angular 2 Router component (RC3 Beta 2).

Anyone know what I'm doing wrong? Thanks in advance.

Netwraith
  • 11
  • 2

3 Answers3

1

This should be:

<a [routerLink]="['page', {'id': item.id}, 'component']">

instead of:

<a [routerLink]="['/page', item.id, 'component']">
Yhlas
  • 411
  • 3
  • 5
  • 17
  • I do the same thing in app I am working on. Perhaps you have error somewhere else. Make sure you have ROUTER_DIRECTIVES in your component directives list. – Yhlas Jul 15 '16 at 18:15
  • Weird. I have the router directives in my directives list as well. – Netwraith Jul 15 '16 at 19:28
  • If you are getting item through service it may be undefined because at the moment you are trying access it. Can you try to `console.log(item)` and see if it is defined? – Yhlas Jul 15 '16 at 20:17
0

Try this

<a [routerLink]="['page', item?.id, 'component']">
Arpit Agarwal
  • 3,993
  • 24
  • 30
  • Thanks. Tried that as well but get a 'Cannot read property 'toString' of undefined ' error, likely referring to 'item'. I'm getting item though through a service and displaying another property from it elsewhere on the page. – Netwraith Jul 15 '16 at 18:41
  • Try adding elvis operator as suggested in my updated answer – Arpit Agarwal Jul 15 '16 at 18:43
  • ah it's says toString in error. This should not be coming on router link. You can inspect the link and it should be formed correctly. You need to se this might be coming from componet you are routing to. – Arpit Agarwal Jul 15 '16 at 19:32
  • Also set enableTracing true in provide router to see at what state of navigation it fails provideRouter(....,{enableTracing:true}) – Arpit Agarwal Jul 15 '16 at 19:33
0

From what I can see, this route configuration doesn't work:

{ path: 'page/:id/component', component: MyComponent, data: {id: 'item.id'} }

I think what you really need to ask is if the final '/component' is necessary. If it is, you might want to consider adding a child route.

Another option would be to alter the order of your route, using page/component/:id instead. I believe the routerlink directive appends your URL search parameters to the end of the route, so this should work.

Again, the easiest solution would be to just remove '/component' from the route configuration.

Jk Jensen
  • 339
  • 2
  • 4
  • 16