Angular, RouterLinkActive including fragments?

Lokesh kumar Jain
2 min readJun 25, 2019

In an Angular application, for routing we use routerActiveLink to add CSS class to the link or the parent element when the user navigates to the links.

<li routerLinkActive="active activeClass2">
<a routerLink="/page">Inicio</a>
</li>

The above code will add active and activeClass2 to the li element when the user navigates to the /page URL.

But sometimes we want to navigate to the section on the page using old school with the help of segments having id attached to the segment/div.

For our project, we used the same page navigation using these segments(id). For the segment navigation on the page, Angular has a directive called fragment. so the code will look live this.

  <li routerLinkActive="active">
<a routerLink="/sitio" fragment="inicio">Inicio</a>
</li>
<li routerLinkActive="active">
<a routerLink="/sitio" fragment="invierte">Invierte</a>
</li>
<li routerLinkActive="active">
<a routerLink="/sitio" fragment="contacto">Contacto</a>
</li>

The above code works, but the problem with the above code is that routerLinkActive will add active class to all the elements.

The solution, for the above problem according to some users is adding [routerLinkActiveOptions]="{ exact: true }" along with the `routerLinkActive`, but this seems to work only after the router version 7.2.4 .

My solution is ActivatedRoute . Inject this into the Component.

class ComponentClass{
activeFragment = this.route.fragment.pipe(share());
constructor(public route: ActivatedRoute){}
}

Now use this in the template as.

<li [class.active]="(activeFragment | async)==='inicio'">
<a routerLink="/sitio" fragment="inicio">Inicio</a>
</li>
<li [class.active]="(activeFragment | async)==='invierte'">
<a routerLink="/sitio" fragment="invierte">Invierte</a>
</li>
<li [class.active]="(activeFragment | async)==='contacto'">
<a routerLink="/sitio" fragment="contacto">Contacto</a>
</li

Let me know if this code helps you or you have a better solution to this.

Thanks!

--

--

Lokesh kumar Jain

Love Web building technologies working as frontend team lead loves working on JavaScript tech stack, as Reactjs, Angular, HTML5