ThreeAccents ThreeAccents - 3 months ago 13
AngularJS Question

Routing variable in Angular2

I've read over the documentation for the new Angular router. The example they have for routing to a variable is this:

Component/Module:

angular.module('myApp', ['ngFuturisticRouter'])
.controller('AppController', ['$router', function($router) {
$router.config({ path: '/user/:id' component: 'user' });
this.user = { name: 'Brian', id: 123 };
});


HTML/Template:

<div ng-controller="AppController as app">
<a router-link="user({id: app.user.id})">{{app.user.name}}</a>
</div>


Here is my component:

@RouteConfig([
{ path: '/', component: Home, as: 'home' },
{ path: '/displays/:id', component: DisplayDetails, as: 'display-details' }
])


And my HTML/Template:

<div class="col-md-3" *ng-for="#display of displays">
<a [router-link]="['/display-details({id: display.id})']"><display-card ></display-card></a>
</div>


I've also tried instead of putting the component alias
(display-details)
I've tried putting the actual path and the component it self but they all give me the same error:

EXCEPTION: Component "App" has no route named "display-details({id: display.id})". in [null]

Answer

As suggested by @ThreeAccents

Quoting from the documentation RouterLink.

RouterLink expects the value to be an array of route names, followed by the params for that level of routing. For instance ['/Team', {teamId: 1}, 'User', {userId: 2}] means that we want to generate a link for the Team route with params {teamId: 1}, and with a child route User with params {userId: 2}.

So the solution is to change your routerLink to as follows :

<div class="col-md-3" *ng-for="#display of displays">
    <a [routerLink]="['/display-details', {id: display.id}]">
       <display-card ></display-card>
    </a>
</div>

Glad it worked for you :)

Comments