简体   繁体   English

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

[英]Angular 2 root's route is always active

Recently I read this useful article about Angular 2 Router and looked at the demo . 最近我读了这篇关于Angular 2 Router的有用文章并看了一下这个演示 Everything seemed to be perfect. 一切似乎都很完美。 But when I tried to determine the active route based on router-link-active class, I found out that the root route always active. 但是当我尝试根据router-link-active类确定活动路由时,我发现根路由始终处于活动状态。

Here is the piece of codes of the app.component.ts where the 'main' routes are configured: 以下是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 { }

If I change the path from '/' to '/home' and <a [routerLink]="['/']">Home</a> to <a [routerLink]="['/home']">Home</a> the default component (which has to be HomeComponent) disappears. 如果我将路径从'/'更改为'/home'并将<a [routerLink]="['/']">Home</a> '/' '/home' <a [routerLink]="['/']">Home</a>更改为<a [routerLink]="['/home']">Home</a>默认组件(必须是HomeComponent)消失。 The HomeComponent will be activated only if the link is clicked and the router-link-active will be added and removed correctly everytime we change to another route. 只有在单击链接时才会激活HomeComponent,并且每次我们更改为另一个路由时,都会正确添加和删除router-link-active

Is this a bug or there is something wrong with the routes' configuration? 这是一个错误还是路由配置有问题?

Adding the following property to your home anchor worked for me. 将以下属性添加到您的主锚为我工作。 [routerLinkActiveOptions]="{ exact: true }"

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

This is how it will work: 这是它的工作方式:

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

Its not a bug to my knowledge, you need to have a fallback component for / or unknown paths. 据我所知,它不是一个错误,你需要有/或未知路径的后备组件。 (most likely HomeComponent) (很可能是HomeComponent)

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

This though is using the new Router module (not the deprecated one) and works in rc.0 and rc.1 这虽然使用新的Router模块(不是已弃用的)并且在rc.0rc.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM