Angular 2 exact RouterLinkActive including fragments?

I just thought I would put how I solved it in case someone runs into the same problem: keep track of the current section in the site and use a class binding through a function in the component instead of using routerLinkActive.

The links in the template become:

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

Note the lack of use of routerLinkActive, and the use of class binding [class.active]=isSectionActive('<name-of-section>') instead.

The code that keeps track of the section we're inside of and decides whether or not to apply the CSS class in the template is:

import { Router, NavigationEnd } from '@angular/router';

// Class signature... {

    private activeSiteSection: string;

    constructor(
        private router: Router,
        private sessionService: SessionService
    ) {
        router.events.subscribe((event) => {
            if(event instanceof NavigationEnd ) {
                this.SiteURLActiveCheck(event);
            }
        });
    }

    private SiteURLActiveCheck(event: NavigationEnd): void {
        if (event.url.indexOf('#inicio') !== -1) {
            this.activeSiteSection = 'inicio';
        } else if (event.url.indexOf('#invierte') !== -1) {
            this.activeSiteSection = 'invierte';
        } else if (event.url.indexOf('#contacto') !== -1) {
            this.activeSiteSection = 'contacto';
        } else {
            this.activeSiteSection = '';
        }
    }

    private isSectionActive(section: string): boolean {
        return section === this.activeSiteSection;
    }
}

Probably overkill but I rather go this route than modify Angular 2's source. :)


There is an open issue to support that https://github.com/angular/angular/issues/13205

routerLinkActive is a simple directive. You might be able to create a clone yourself with that extended functionality.