填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

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()
routerLinkActiveOptions: { exact: boolean; } | IsActiveMatchOptions

Options to configure how to determine if the router link is active.

These options are passed to the Router.isActive() function.

參見:

  • Router.isActive

@Input()
routerLinkActive: string | string[]
只寫

範本變數參考手冊

識別符號用途
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>