0

我使用 router.isActiveRoute 来确定哪个路由是活动的。在我第一次路由到home linkormenu link时,路由更改但未添加活动类。active class在第二次单击时添加。

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

应用程序.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));
    }
}

应用程序.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>

谢谢

4

2 回答 2

2

解决方案很简单。将 angular2-polyfills.js 移动到 system.js 脚本标签下面就可以了。这是一个已知问题#6140。还有一个演示链接

@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 { }
于 2016-01-16T05:33:37.173 回答
1

如果您使用的是 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>
于 2017-10-11T10:26:14.060 回答