填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

RouterLinkActive

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.

查看"说明"...

NgModule

选择器

属性

属性说明
links: QueryList<RouterLink>
linksWithHrefs: QueryList<RouterLinkWithHref>
isActive: boolean只读
@Input()
routerLinkActiveOptions: { exact: boolean; }
@Input()
routerLinkActive: string | string[]
Write-only.

模板变量参考手册

标识符用途
routerLinkActive#myTemplateVar="routerLinkActive"

说明

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 the router activates the associated route:

<a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
      
      <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>
      
      <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>
      
      <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
true}">Bob</a>
    

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>
      
      <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>
      
      <div routerLinkActive="active-link">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>