Angular 2 root's route is always active

2020-07-03 08:43发布

问题:

Recently I read this useful article about Angular 2 Router and looked at the demo. 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.

Here is the piece of codes of the app.component.ts where the 'main' routes are configured:

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

Is this a bug or there is something wrong with the routes' configuration?

回答1:

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



回答2:

This is how it will work:

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


回答3:

Its not a bug to my knowledge, you need to have a fallback component for / or unknown paths. (most likely 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