在Angular 2中,router.isActiveRoute第一次不工作

时间:2016-01-14 16:59:05

标签: angularjs angular2-routing

我使用router.isActiveRoute来确定哪条路线是活动的。 我第一次路由到home linkmenu link时,路线会发生变化,但不会添加有效课程。第二次点击会添加active class

我认为它是angular2中Router指令的错误。 请告诉我为什么以及如何解决它?

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>

由于

2 个答案:

答案 0 :(得分:2)

解决方案很简单。在system.js脚本标记下面移动angular2-polyfills.js就可以了。 这是一个已知问题#6140。 还有demo link

@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 { }

答案 1 :(得分:0)

如果您正在使用Angular 4+,则应使用routerLinkActive="active"指令而不是使用任何其他复杂过程来确定当前路由未知时的活动路由。

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