RouterLinkActive In Angular
In this article, we learn what is RouterLinkActive and how to use RouterLinkActive In Angular. The RouterLinkActive directive allows you to add or remove classes from a RouterLink-bound HTML element. We may use this directive to change the CSS classes for active Router Links depending on the RouterState. This directive's primary purpose is to indicate which route is currently active. You can make the font strong or use a different backdrop color.
RouterLinkActive
Along with the RouterLink directive, the RouterLinkActive directive is used. A Template expression can be found on the right-hand side of RouterLinkActive. When the route is active, the template expression must contain a space-delimited string of CSS classes that will be applied to the element.
Take a look at the following examples.
<li><a [routerLink]="['home']" routerLinkActive="active">Home</a></li> <li><a [routerLink]="['product']" [routerLinkActive]="['active']">Product</a></li>
The global styles are determined by the CSS Rule.
.active { background-color: yellow; }
Multiple classes
<a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a> <li><a [routerLink]="['home']" routerLinkActive="active home">Home</a></li> <li><a [routerLink]="['product']" [routerLinkActive]="['active','home']">Product</a></li>
Child Routes
<a routerLink="/product" routerLinkActive="class1 class2">Product</a> <a routerLink="/product/PC" routerLinkActive="class1 class2">PC</a> <a routerLink="/product/mobile" routerLinkActive="class1 class2">Mobile</a>
Exact matching
<a routerLink="/product" routerLinkActive="class1 class1" [routerLinkActiveOptions]="{exact:true}">Product</a> <a routerLink="/product/PC" routerLinkActive="class1 class2">PC</a> <a routerLink="/product/mobile" routerLinkActive="class1 class2">Mobile</a>
Matching
without exact: true
- Only a portion of the queryParams is matched.
- The URL tree has a subtree called URL.
- Parameters in the matrix are disregarded.
with exact: true
- a question Parameters must be identical.
- The URL must be identical.
- Parameters in the matrix are disregarded.
Adding classes to ancestors
<div routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}"> <a routerLink="/product/pc">Jim</a> <a routerLink="/product/mobile">Bob</a> </div>
Bind to Component Property
<li><a [routerLink]="['home']" routerLinkActive="{{getClass()}}">Home</a></li>
In component class
getClass() { return "active" }