0%

angular-router-style

This post will show you how to style the active link in Angular Router with routerLinkActive and routerLinkActiveOptions.

routerLinkActive

routerLinkActive is a directive that adds a CSS class to the element when the link’s route becomes active.

We set a class name active to the active link, and apply a red background color to the active link. When user click the home or about link, the background color of the active link will change to red.

1
2
3
4
5
6
<ul>
<li><a routerLink="/home" routerLinkActive="active">Home</a></li>
<li><a routerLink="/about" routerLinkActive="active">About</a></li>
</ul>

<router-outlet/>
1
2
3
.active {
background-color: red;
}

routerLinkActiveOptions

routerLinkActiveOptions is an input property of routerLinkActive directive that allows you to set the options for the active link. It provides a finer-grained control over the behavior of the active link.

Let’s take a look at the definition of routerLinkActiveOptions:

1
2
3
4
5
6
7
8
9
10
routerLinkActiveOptions: {
exact: boolean;
} | IsActiveMatchOptions;

export declare interface IsActiveMatchOptions {
matrixParams: 'exact' | 'subset' | 'ignored';
queryParams: 'exact' | 'subset' | 'ignored';
paths: 'exact' | 'subset';
fragment: 'exact' | 'ignored';
}

Scenario 1: exact: true

When exact: true, the active link will only be set when the URL is exactly the same as the link’s URL.

1
2
3
4
<ul>
<li><a routerLink="/home" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a></li>
<li><a routerLink="/about" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">About</a></li>
</ul>

With this settings, when user input /home/123 in the browser, the home link will not be active, since /home is not exactly the same as /home/123.

Scenario 2: match fragment

When fragment: 'exact', the active link will only be set when the URL’s fragment is exactly the same as the link’s fragment.

1
2
3
4
5
6
const isActiveMatchOptions: IsActiveMatchOptions = {
matrixParams: 'exact',
queryParams: 'exact',
paths: 'exact',
fragment: 'exact'
};
1
2
3
4
<ul>
<li><a routerLink="/home" routerLinkActive="active" [routerLinkActiveOptions]="isActiveMatchOptions">Home</a></li>
<li><a routerLink="/about" routerLinkActive="active" [routerLinkActiveOptions]="isActiveMatchOptions">About</a></li>
</ul>

With this settings, when user input /home#section1 in the browser, the home link will not be active, since the fragment is not exactly the same as the link’s fragment.

You can also config the matrixParams, queryParams, and paths in the IsActiveMatchOptions object to control the active link behavior.