Help Angular by taking a 1 minute survey!Go to surveyHome

RouterLinkActive

Lets you add a CSS class to an element when the link's route becomes active.

See more...

NgModule

Selectors

Properties

Property Description
links: QueryList<RouterLink>
linksWithHrefs: QueryList<RouterLinkWithHref>
isActive: boolean Read-only.
@Input()
routerLinkActiveOptions: { exact: boolean; }
@Input()
routerLinkActive: string | string[]
Write-only.

Template variable references

Identifier Usage
routerLinkActive #myTemplateVar="routerLinkActive"

Description

This directive lets you add a CSS class to an element when the link's route becomes active.

Consider the following example:

<a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
      
      <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
    

When the url is either '/user' or '/user/bob', the active-link class will be added to the a tag. If the url changes, the class will be removed.

You can set more than one class, as follows:

<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>
    

You can configure RouterLinkActive by passing exact: true. This will add the classes only when the url matches the link exactly.

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

You can assign the RouterLinkActive instance to a template variable and directly check the isActive status.

<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>
    

Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink.

<div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}"> <a routerLink="/user/jim">Jim</a> <a routerLink="/user/bob">Bob</a> </div>
      
      <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>
    

This will set the active-link class on the div tag if the url is either '/user/jim' or '/user/bob'.

Methods

ngAfterContentInit(): void
      
      ngAfterContentInit(): void
    
Parameters

There are no parameters.

Returns

void

ngOnChanges(changes: SimpleChanges): void
      
      ngOnChanges(changes: SimpleChanges): void
    
Parameters
changes SimpleChanges
Returns

void

ngOnDestroy(): void
      
      ngOnDestroy(): void
    
Parameters

There are no parameters.

Returns

void