Farshad Momtaz Farshad Momtaz - 2 months ago 25
TypeScript Question

undefined root error when using routerLinkeActive in Angular 2

I'm using AngularJS 2 to create a SPA application. I'm trying to add a class to the button for the active path. According to the Angular 2's router documentation I should use the

directive to add a class. However when I do so I get
Cannot read property 'root' of undefined
error. The app works perfectly if I remove the
from the template.

Router code:

export const routes: RouterConfig = [
{path : '', redirectTo: 'home', pathMatch: 'full'},
{path : 'home', component : HomeComponent}
{path : 'item', component : ItemListComponent}
{path : 'item/:id', component : ItemComponent},

export const APP_ROUTER_PROVIDERS = [

HTML template code:

<button [routerLink]="['home']" class="btn btn-block" routerLinkActive="active">Home</button>
<button [routerLink]="['item']" class="btn btn-block">Items</button>

Component Code:

selector: 'home-page',
directives: [ROUTER_DIRECTIVES],
precompile: [HomeComponent, ItemListComponent],
templateUrl: `app/templates/main-page.template.html`
export class HomePageComponent { }


EXCEPTION: Error in app/templates/main-page.template.html:15:8
ORIGINAL EXCEPTION: TypeError: Cannot read property 'root' of undefined

What is the root propery and where should I define it?


The undefined root error is a bug in the current release of angular2 (2.0.0-rc.4) that doesn't allow routeLink to be used with non-anchor tags if routerLinkActive is present. The issue seems fixed in master (see: https://github.com/angular/angular/issues/9755)

For the current release you would need to wrap the button around an anchor tag. It should look something like this:

<a routerLink="/home" routerLinkActive="active">
    <button class="btn btn-block" >Home</button>

<a routerLink="/item">
    <button class="btn btn-block">Items</button>