Angular 2 root的路由始终处于活动状态

时间:2016-06-09 01:22:42

标签: javascript angular

最近我看了this useful article about Angular 2 Router并查看了the demo。一切似乎都很完美。但是当我尝试根据router-link-active类确定活动路由时,我发现根路由始终处于活动状态。

以下是app.component.ts的代码段,其中' main'路线配置:

@Component({
  selector: 'demo-app',
  template: `
    <a [routerLink]="['/']">Home</a>
      <a [routerLink]="['/about']">About</a>
    <div class="outer-outlet">
      <router-outlet></router-outlet>
    </div>
  `,
  // add our router directives we will be using
  directives: [ROUTER_DIRECTIVES]
})
@Routes([
    // these are our two routes
    { path: '/', name: 'Home', component: HomeComponent }, // , useAsDefault: true}, // coming soon
    { path: '/about', name: 'About', component: AboutComponent }
])
export class AppComponent { }

如果我将路径从'/'更改为'/home'并将<a [routerLink]="['/']">Home</a>更改为<a [routerLink]="['/home']">Home</a>,则默认组件(必须是HomeComponent)会消失。只有在点击链接时才会激活HomeComponent,并且每次我们更改为另一条路线时都会正确添加和删除router-link-active

这是一个错误或路线有什么问题&#39;配置?

3 个答案:

答案 0 :(得分:22)

将以下属性添加到您的主锚中对我有用。 [routerLinkActiveOptions]="{ exact: true }"

了解更多https://github.com/angular/angular/issues/8397#issuecomment-237314970

答案 1 :(得分:0)

据我所知,这不是一个错误,您需要为/或未知路径设置一个回退组件。 (很可能是HomeComponent)

@Routes([
  { path: '/home', component: HomeComponent },
  { path: '/about', component: AboutComponent },
  { path: '*', name: component: HomeComponent }
]);

这虽然使用了新的Router模块(不是已弃用的模块)但适用于rc.0rc.1

答案 2 :(得分:0)

这是如何运作的:

<nav>
    <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a>
    <a routerLink="/about" routerLinkActive="active">About</a>
</nav>
相关问题