首页 文章

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

提问于
浏览
10

最近我读了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 .

这是一个错误还是路由配置有问题?

3 回答

  • 0

    将以下属性添加到您的主锚为我工作 . [routerLinkActiveOptions]="{ exact: true }"

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

  • 0

    据我所知,它不是一个错误,你需要为 / 或未知路径提供后备组件 . (很可能是HomeComponent)

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

    这虽然使用新的 Router 模块(不是已弃用的)并且在 rc.0rc.1 中工作

  • 20

    这是它的工作方式:

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

相关问题