How to Mark a Link as Active in Angular, Even if the Query Params Are Different

#WhatILearnedToday in Angular: how to mark a link as active, ignoring the query params

I’ve known for a while how to use Angular to mark a link as the currently active link. For example, in Angular Boot Camp’s Routing and Lazy Loading lesson, “HR” has a green background when the url ends in “/hr”, and “Payroll” has a green background when the url instead ends in “/payroll”.

We achieve this by putting the RouterLinkActive directive on the link in question; whatever string you pass into that directive becomes a CSS class that is added if and only if that link is currently routed to.

But what if there are query params in your routing? What if the HR page sometimes has the url of “/hr”, but it’s sometime “/hr?search=foo”? And what if the navigation link points to “hr?search=foo” when your app is currently at “/hr?search=bar” instead?

By default, the HR link won’t be marked as active if the query params disagree like that. Fortunately, it’s easy to tell RouterLinkActive which differences in the routing to care about, and that’s what I learned this week.

How to do it

The RouterLinkActive directive takes an input called routerLinkActiveOptions, with this shape:

routerLinkActiveOptions: {
    exact: boolean;
} | IsActiveMatchOptions

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

So, you can pass in a small object that tells RouterLinkActive exactly which parts of the url to pay attention to. In some cases, the short version works to pass in a single boolean, but I needed to define the queryParams property as 'ignored', so I needed the full version:

  readonly myMatchOptions: IsActiveMatchOptions = {
    queryParams: 'ignored',
    matrixParams: 'exact',
    paths: 'exact',
    fragment: 'exact',
  };

  <li routerLinkActive="green-background" [routerLinkActiveOptions]="myMatchOptions">
    <a routerLink="/hr" [queryParams]="currentParams">HR</a>
  </li>

About Lance Finney

Father of two boys, Angular/TypeScript developer, Ethical Humanist, and world traveler (when I can sneak it in). Contributor to Grounded Parents.
This entry was posted in default, Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s