Angular 2 routerlink with multiple routes?
I want to remove a class on only one ONE route (or add a class on all BUT only one route.) How is this possible? I've tried [routerLink] with multiple parameters to no avail:
<div class='body-content' [routerLink]="['/fetch-data', '/counter']" [routerLinkActive]="['col-sm-9']" >
<router-outlet></router-outlet>
</div>
Or is there such a thing as [routerLinkNOTActive] or something similar:
<div class='body-content' [routerLink]="['/home']" [routerLinkNotActive]="['col-sm-9']">
then it will add the class "col-sm-9" on all routes that are not "/ home". Seems very simple but can't find anything to do it.
+3
source to share
2 answers
I don't know if there is a built-in directive to do what you want, but you can always add some logic to your component.
In your template ,
<div class='body-content' [routerLink]="['/fetch-data', '/counter']" [class]="bodyContentClass()">
And in your component ,
bodyContentClass() {
// router is an instance of Router, injected in the constructor
return this.router.isActive('/url-to-make-body-active') || this.router.isActive('/other-url-to-make-body-active') ? 'col-sm-9' : '';
}
You can have fun and test any combination of the routes you want.
+3
source to share
Here's my final solution, which just used the [class] attribute. BTW, what happened to the [ng-class] attribute in Angular2 ?:
HTML:
<div class='body-content' [class]="bodyContentClass()" >
<router-outlet></router-outlet>
</div>
TypeScript:
import {Location} from '@angular/common';
...
constructor(private authService: AuthService,private location: Location) { }
...
bodyContentClass()
{
// router is an instance of Router, injected in the constructor
var viewLocation = location.pathname;
return viewLocation == '/counter' || viewLocation == '/fetch-data' ? 'col-sm-9' : '';
}
0
source to share