RouterLinkActive
跟踪元素上的链接路由当前是否处于活动状态,并允许你指定一个或多个 CSS 类,以便在链接路由处于活动状态时添加到该元素。
Tracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active.
Exported from
选择器
属性
属性 | 说明 |
---|---|
links: QueryList<RouterLink> | |
linksWithHrefs: QueryList<RouterLinkWithHref> | |
isActive: boolean | 只读 |
@Input() | Options to configure how to determine if the router link is active. These options are passed to the 参见:
|
@Input() | 只写 |
模板变量参考手册
标识符 | 用途 |
---|---|
routerLinkActive | #myTemplateVar="routerLinkActive" |
说明
使用此指令为与活动路径关联的元素创建视觉差异。例如,以下代码会在路由器激活关联的路由时突出显示单词 “Bob”:
Use this directive to create a visual distinction for elements associated with an active route. For example, the following code highlights the word "Bob" when the router activates the associated route:
<a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
当浏览器的当前 url 是 '/user' 或 '/user/bob' 时,就会往 a
标签上添加 active-link
类; 如果 url 发生了变化,则移除它。
Whenever the URL is either '/user' or '/user/bob', the "active-link" class is added to the anchor tag. If the URL changes, the class is removed.
你可以设置一个或多个类,例如:
You can set more than one class using a space-separated string or an array. For example:
<a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
<a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
你可以通过传入 exact: true
来配置 RouterLinkActive。这样,只有当 url 和此链接精确匹配时才会添加这些类。
To add the classes only when the URL matches the link exactly, add the option exact: true
:
<a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
true}">Bob</a>
要直接检查 isActive
状态,请将 RouterLinkActive
实例分配给模板变量。例如,以下代码会在不分配任何 CSS 类的情况下检查状态:
To directly check the isActive
status of the link, assign the RouterLinkActive
instance to a template variable. For example, the following checks the status without assigning any CSS classes:
<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
Bob {{ rla.isActive ? '(already open)' : ''}}
</a>
最后,你还可以把 RouterLinkActive
指令用在 RouterLink
的各级祖先节点上。
You can apply the RouterLinkActive
directive to an ancestor of linked elements. For example, the following sets the active-link class on the <div>
parent tag when the URL is either '/user/jim' or '/user/bob'.
<div routerLinkActive="active-link">
<a routerLink="/user/jim">Jim</a>
<a routerLink="/user/bob">Bob</a>
</div>