Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Active tab in navbar when router.navigate is used

I'm using Angular 2 with Bootstrap 4. I can get the active tab to change using the following code:

navbar.component.html

<nav class="navbar navbar-fixed-top navbar-light bg-faded">
  <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#navbar">
    &#9776;
  </button>
  <div class="collapse navbar-toggleable-xs" id="navbar">
  <div class="container">
    <a class="navbar-brand" [routerLink]="['']">My App</a>
    <ul class="nav navbar-nav navbar-right">
      <li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact:
true}">
        <a class="nav-link" [routerLink]="['']">Home<span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
        <a class="nav-link" [routerLink]="['/about']">About</a>
      </li>
      <li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
        <a class="nav-link" [routerLink]="['/example']">Example</a>
      </li>      
    </ul>
  </div>
  </div>
</nav>

The line:

[routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}"

works well at changing to the currently active tab, but when I navigate to a component using something like:

this.router.navigate(['']);

The active tab doesn't change. Is there a way to change the active tab when navigating like above?

like image 760
Bhetzie Avatar asked Sep 16 '16 13:09

Bhetzie


People also ask

How do I make navbar tab active on click?

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.

How do I know if my routerLink is active?

routerLinkActive is simply an indicator of whether this link represents the active route. @jessepinho - Tried it - [routerLinkActive]="'active'" will only work if you also have [routerLink] in the a-tag. If you had (click)="navitageTo('/route')" instead of [routerLink], and in that function, you called this.

What is routerLinkActive active?

RouterLinkActivelinkTracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active.


1 Answers

So basically you want to make your high-lighting in a service and call that service to apply your style when your URL equals a specific state. this is done by using

this.router.url === '/myroute'

here is my plunker. NOTE that the active tab will change whether you use the links or the buttons. The buttons are what use the this.router.navigate(['']); like you asked in the question

like image 195
Bean0341 Avatar answered Sep 29 '22 12:09

Bean0341