4
votes

I'm using angular2 and angular2 [routerLinkActive] on each link, to set the active link. This all works fine. When the user clicks on a link, the route becomes active and the link gets the "active" class injected and I can style accordingly.

However in the route setup I set up a default route like so:

const routes: Routes = [
{ path: '', redirectTo: 'gettiingstarted', pathMatch: 'full' },

This works in as far as the page now successfully loads the "gettingstarted" component when the user first navigates to the page, but unfortunately the router link has not had the "active" class injected at this point, so is not correctly styled. The only way to get the active class is to actually click the link.

Does anyone know how I can get [routerLinkActive] mechanism to work on page load?

Update Here is the code html for the link itself:

 <a [routerLink]="['gettingstarted']" [routerLinkActive]="['active']">
2
Look at the docs, there are couple of options you can try [routerLinkActiveOptions]="{exact: true}, for example.Sasxa
show how you have your routerLinkActive is used, and the route you're navigating toMax Koretskyi
why are you using =['gettingstarted'] instead of ="gettingstarted"?Max Koretskyi
and [routerLinkActive]= instead of routerLinkActive=?Max Koretskyi
My understanding is that angular2 supports both of these syntaxes, certainly this syntax has not been an issue anywhere else. I have tried the "{exact: true}" and this had no effect.Slicc

2 Answers

4
votes

Putting the following in the constructor of the app.component.ts file fixed it:

        this.router.navigate(['/gettingstarted']);

Not sure it is the recommended solution, but fixes it for my case.

1
votes

Use isActive: true in routerLinkActiveOptions like this

<a routerLinkActive="active-link" [routerLinkActiveOptions]="{ exact: true, isActive: true }">Home</a>