I just thought that I would set it, as I solved it, if someone encounters the same problem: track the current section of the site and use the class binding through the function in the component instead of routerLinkActive
.
Links in the template will 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 using routerLinkActive
and the use of class binding [class.active]=isSectionActive('<name-of-section>')
.
The code that tracks the section we are in and determines whether to apply the CSS class in the template:
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 too much, but I would rather go this route than change the source of Angular 2. :)
source share