Update March 2021
Angular team finally merge the PR for that, you can looks at https://github.com/angular/angular/pull/40303 for more detail.
To use it, simply put
<div routerLinkActive="active-link" [routerLinkActiveOptions]="options">
</div>
Where options
will have the either the shape of IsActiveMatchOptions
export declare interface IsActiveMatchOptions {
fragment: 'exact' | 'ignored';
matrixParams: 'exact' | 'subset' | 'ignored';
paths: 'exact' | 'subset';
queryParams: 'exact' | 'subset' | 'ignored';
}
or simply accept a boolean exact
{
exact: boolean
}
Original Question
I am using routerLink in Angular as below
<li routerLinkActive="active">
<a [routerLink]="['/view', 10]"
[queryParams]="{'offset': 0, 'numberOfItems': 100}"
queryParamsHandling="merge">
<div>View</div>
<div><span class="badge" [innerHtml]="viewCount"></span></div>
</a>
</li>
So the .active class was added to li tag when the URL looks like
/view/10?offset=0&numberOfItems=100
If the URL was changed either offset
or numberOfItems
to a different value, the .active class will be removed, such as.
/view/10?offset=0&numberOfItems=120
I went through the angular docs and managed to make it works by adding another routerLink but make it hidden as below.
<li routerLinkActive="active">
<a [routerLink]="['/view', 10]"
[queryParams]="{'offset': 0, 'numberOfItems': 100}"
queryParamsHandling="merge">
<div>View</div>
<div><span class="badge" [innerHtml]="viewCount"></span></div>
</a>
<a [routerLink]="['/view', 10]" style="display:none;">
<div><span class="badge" [innerHtml]="viewCount"></span></div>
</a>
</li>
Seem the above approach is a little hack. Is there any configuration that I can set to make routerLinkActive works when router parameter presents with optional query parameter?
<a>
tag? If that is the default values, shouldn't they be set inside the destination component itself? In that case, you will only need one<a>
here. – Harry Ninh