How can I set Bootstrap navbar "active" class in Angular 2? I only found Angular 1 way.
When I go to About page, add class="active"
to About, and remove class="active"
on Home.
<ul class="nav navbar-nav">
<li class="active"><a [routerLink]="['Home']">Home</a></li>
<li><a [routerLink]="['About']">About</a></li></li>
</ul>
Thanks
To set an active class in your bootstrap navbar, you can use ng-controller(NavigationController) to set bootstrap navbar active class with AngularJS. To run a single controller outside ng-view. You can set class= “active” when the angular route is clicked.
To set the active class to the navigation menu dynamically by scrolling or clicking on the navigation links, the active class is to be set on each section depending on the position of the webpage. To add methods and variables, JavaScript is used.
To make the clicked tab active in the navigation bar, the <li> corresponding to the clicked href in index. html introduces the css of 'active' class and removes the 'active' class from the previous <li> on click.
To create a collapsible navigation bar, use a button with class="navbar-toggler", data-toggle="collapse" and data-target="#thetarget" . Then wrap the navbar content (links, etc) inside a div element with class="collapse navbar-collapse" , followed by an id that matches the data-target of the button: "thetarget".
If you use the new 3.0.0. component router ( https://github.com/angular/vladivostok ) you can use the routerLinkActive directive. No further javascript required.
<ul class="nav navbar-nav">
<li [routerLinkActive]="['active']"> <a [routerLink]="['one']">One</a></li>
<li [routerLinkActive]="['active']"> <a [routerLink]="['second']">Second</a></li>
</ul>
I used "@angular/router": "^3.0.0-alpha.7"
Bert Deterd's answer is correct, but there's one thing that can be added.
If one route is a substring of another route, you will see something like this happen: 2 active anchors
You can add this to make it match exact routes only:
[routerLinkActiveOptions]="{exact:true}"
Full Example:
<ul class="nav navbar-nav">
<li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/']">Home</a>
</li>
<li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/about']">About</a>
</li>
<li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/calendar']">Calendar</a>
</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With