How do we style an element with css-class "active" with the new angular2.rc3 & router3.0.0alpha6?
The old approaches do not seem to work any more and there is little documentation yet on the finer details of the new router...
How do we style an element with css-class "active" with the new angular2.rc3 & router3.0.0alpha6?
The old approaches do not seem to work any more and there is little documentation yet on the finer details of the new router...
Thanks sanket to pointing me to the other thread!
It seems in v3 the router does have an easily accessible way to get the current route:
this.router.url
So a possible solution to style the active route component with a css class is:
<li [class.active]="isActiveRoute('/myroute')">
<a [routerLink]="['/myroute']">
</li>
and in your navigation / menu component:
isActiveRoute(route: string) : boolean
{
if(this.router.url === route)
{
return true;
}
else
{
return false;
}
}
If you want to set something on the actual routerLink
anchor there's some functionality now in V3 to make it a little easier:
<li>
<a [routerLink]="['/']" routerLinkActive="router-link-active">Home</a>
</li>
Where whatever you put equal to routerLinkActive
will become the class of the anchor if that route is currently active. Not sure if that's exactly what you're looking for though.
I found this information out via searching the Angular2
issues on their Github Repo: https://github.com/angular/angular/issues/9426. Sounds like there's talk of having some default behavior where a class router-link-active
is set to the currently active route anchor (as it was in previous versions of the router).
EDIT: If for some reason you want to add a class to an element outside of the html with routerLink, etc.
here's a way I've cobbled together:
export class App implements OnInit, OnDestroy {
@HostBinding('class.home') isHome = false;
constructor(router: Router, route: ActivatedRoute) {
this.router = router;
}
ngOnInit() {
this.sub = this.router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
this.isHome = e.url === '/';
}
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
Reference: https://stackoverflow.com/a/37931429/6417489