Farshad Momtaz Farshad Momtaz - 4 months ago 41
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

RouterLinkActive
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
routerLinkActive="active"
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 = [
provideRouter(routes)
];


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:

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


Error:

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?

Answer

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>

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