简体   繁体   English

Angular 2 routerLinkActive 对于基本路径始终处于活动状态

[英]Angular 2 routerLinkActive always active for base path

I have this code for my navbar:我的导航栏有以下代码:

<nav>
  <a [routerLink]="['/']" [routerLinkActive]="['nav-active']">HOME</a>
  <a [routerLink]="['/about']" [routerLinkActive]="['nav-active']">ABOUT</a>
  <a [routerLink]="['/records']" [routerLinkActive]="['nav-active']">RECORDS</a>
</nav>

The problem is the HOME nav point always gets the class because / seems to be always active.问题是 HOME 导航点总是获得类,因为 / 似乎总是处于活动状态。 Is this avoidable with a small and simple solution?这可以通过一个小而简单的解决方案来避免吗?

Thanks for the help谢谢您的帮助

Edit:编辑:

this is the solution for now:这是目前的解决方案:

[routerLinkActiveOptions]="{ exact: true }" [routerLinkActiveOptions]="{ 准确:真 }"

As suggested by @TomRaine in this answer , you can add the property [routerLinkActiveOptions]="{ exact: true }" to your element:正如@TomRaine 在此答案中所建议的那样,您可以将属性[routerLinkActiveOptions]="{ exact: true }"添加到您的元素中:

<nav>
  <a [routerLink]="['/']" 
      [routerLinkActive]="['nav-active']"
      [routerLinkActiveOptions]="{ exact: true }">
    HOME
  </a>
  ...
</nav>

This appears to be a known issue.这似乎是一个已知问题。 A few workarounds are detailed in this thread: https://github.com/angular/angular/issues/8397此线程中详细介绍了一些解决方法: https ://github.com/angular/angular/issues/8397

From Github Thread:来自 Github 线程:

"you need to add an additional option to your routerLink." “您需要为您的 routerLink 添加一个附加选项。”

[routerLinkActiveOptions]="{ exact: true }"

Then your home route will only be active if you're on the exact route.然后,只有当您在确切的路线上时,您的回家路线才会处于活动状态。 The home route with an empty path will be a partial match on all routes具有空路径的主路由将在所有路由上部分匹配

You can do something like this:你可以这样做:

<button routerLink="/" [routerLinkActiveOptions]="{ exact: true }" routerLinkActive="nav-button-active"
                mat-button mat-raised-button
                class="w-100 mb-3 nav-buttons">
          Dashboard
</button>

Just make rure to add the property, [routerLinkActiveOptions]="{ exact: true }" .只需添加属性[routerLinkActiveOptions]="{ exact: true }"

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

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