Active routerLinkActive with multiple routes

· 324 words · 2 minute read

The routerLinkActive directive lets you add a class to an element when the current location matches a routerLink destination.

Let’s see it with an example:

<a routerLink="/home" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>

That’s the basic use of the routerLink and routerLinkActive directives. We have a couple of links to different pages in our site. If the current location is /home, Angular will add the active class to the first element. If we navigate to the /about page, Angular will remove the first active class, and it will add it to the about link.

This is extraordinarily helpful when building common headers and navigation menus. That type of components is rendered once outside of the router-outlet. With this mechanism, we can mark the current page with some CSS styles.

If we need to style the parent component of the active routerLink, we can do it. The
routerLinkActive directive also detects child nested routerLink elements and reacts accordingly. For example,

<div routerLinkActive="active">
  <a routerLink="/home">Home</a>
</div>

<div routerLinkActive="active">
  <a routerLink="/about">About</a>
</div>

This way, we can add the active class to an upper element.

Now, I want to comment on another, more strange, use case. The one that name this post. Big applications, often have a complex routing definition. Sometimes different routes render the same component, or we want to activate one element for different routes. In these cases, how can we activate one element? can routerLinkActivate react to different routes? Yes, we can use multiple routes inside one routerLinkActive:

<div routerLinkActive="active">
  <a routerLink="/home">Home</a>
  <a routerLink="/about">About</a>
</div>

If the current location is Home or About, Angular will add the active class to the parent div. Even more, if you only want to show one link, you can hide the other element with something like:

<div routerLinkActive="active">
  <a routerLink="/home-mobile" style="display: none">Home</a>
  <a routerLink="/home-desktop">Home</a>
</div>

Now, Angular will add the active class when you are located in any of the two routes, and the user will see one of them only.