Search code examples
angularangular2-routing

Angular2 default active link on site load


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']">

Solution

  • 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.