为什么Angular2 routerLinkActive将活动类设置为多个链接? [英] Why Angular2 routerLinkActive sets active class to multiple links?

查看:82
本文介绍了为什么Angular2 routerLinkActive将活动类设置为多个链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对我的应用程序实现routerLinkActive,但是我面临的问题是,它会将类设置为对多个链接有效.这是我的做法

I'm trying to implement routerLinkActive to my app but i'm facing the issue that it's sets class active to multiple links. Here's how i'm doing it

<ul class="nav nav-tabs">
  <li role="presentation" [routerLinkActive]="['active']"><a [routerLink]="['/']">Home</a></li>
  <li role="presentation" [routerLinkActive]="['active']"><a [routerLink]="['/about']">About</a></li>
  <li role="presentation" [routerLinkActive]="['active']"><a [routerLink]="['/contact']" >Contact Us</a></li>  
</ul>

这就是它的样子

这就是在开发工具中的样子 还有我的地址栏

Here it's how it look in dev-tools And my address bar

推荐答案

尝试将[routerLinkActiveOptions]="{exact: true}"设置为HTML,如下所示:

Try to set [routerLinkActiveOptions]="{exact: true}" to HTML as below :

<ul class="nav nav-tabs">
  <li role="presentation" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}"><a [routerLink]="['/']">Home</a></li>
  <li role="presentation" routerLinkActive="active"><a [routerLink]="['/about']">About</a></li>
  <li role="presentation" routerLinkActive="active"><a [routerLink]="['/contact']" >Contact Us</a></li>  
</ul>

它如何工作?

RouterLinkActive会对当前路由进行分块,并尝试将其部分与您提供的RouterLink进行匹配.考虑到这一点,路由/将在任何地方匹配,因为它是所有其他路由的父级(例如/about/contact等,因为它由/ + route-path组成).为简化起见,这不是错误,它有时是应用程序中匹配多个路由的必需功能.为防止这种情况,您可以指定routerLinkActiveOptions使其与您所走的路线完全匹配.这意味着它不会与父路由匹配,而只会尝试找到为此确切路由提供的routerLink.

How does it work ?

RouterLinkActive does chunk the current route and try to match it's parts with the RouterLinks you've provided. With that in mind, route / will be matched anywhere as it's the very parent for all the other routes (like /about, /contact, etc. as it consist of / + route-path). To simplify, it's not a bug, it's sometimes a needed functionality in your application to match multiple routes. To prevent that, you can specify the routerLinkActiveOptions to match exactly the route you're on. That means it's not going to match parent routes but will only try to found the routerLink provided for this exact route.

这篇关于为什么Angular2 routerLinkActive将活动类设置为多个链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆