0
votes

I use router.isActiveRoute to determine which route is active. At the first time I route to home link or menu link, the route changes but active class isn't added. active class is added at the second click.

I think it's bug of Router directive in angular2. Please tell me why and how to fix it?

app.ts

...
@Component({
    selector: 'app',
    directives: [ROUTER_DIRECTIVES],
    templateUrl: 'app/components/app.html',
    styleUrls: ['app/components/app.css']
})
@RouteConfig([
    { path: '/', component: Home, name: 'Home'},
    { path: '/menu', component: Menu, name: 'Menu'}
])
class AppComponent {
    constructor(public router: Router) {
    }
    isActiveRoutes(routes) {
        return this.router.isRouteActive(this.router.generate(routes));
    }
}

app.html

<a [routerLink]="['Home']">
    <div class="icon-box" [class.active]="isActiveRoutes(['/Home'])">
        <i class="icon ion-ios-list-outline"></i>
    </div>
</a>
<a [routerLink]="['Menu']">
    <div class="icon-box" [class.active]="isActiveRoutes(['/Menu'])">
        <i class="icon ion-ios-bookmarks-outline"></i>
    </div>
</a>
<router-outlet></router-outlet>

Thanks

2

2 Answers

2
votes

The solution is easy. Moving angular2-polyfills.js below system.js script tag did the trick. This is a known issue #6140. There is a demo link also.

@Component({
  selector: 'my-app', 
  providers: [],
  template: `
    <div>
        <ul>
          <li>
            <a [routerLink]="['First']">First</a>
          </li>
          <li>
            <a [routerLink]="['Second']">Second</a>
          </li>
          <li>
            <a [routerLink]="['Third']">Third</a>
          </li>
        </ul>
    </div>
    <router-outlet></router-outlet>
  `,
  styles: [".router-link-active { background-color: red; }"],
  directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  {path: "/first", name: "First", component: FirstComponent},
  {path: "/second", name: "Second", component: SecondComponent},
  {path: "/third", name: "Third", component: ThirdComponent}
])
export class App { }
0
votes

If you're using Angular 4+, you should use routerLinkActive="active" directive instead of using any other complex procedures to determine what is the active route when the current route is not known.

      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" routerLink="/home">Home</a>
      </li>
      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" routerLink="/about-us">About Us</a>
      </li>
      <li class="nav-item" routerLinkActive="active">
        <a title="Contact Us" class="nav-link " routerLink="/contact-us">Contact</a>
      </li>