Bhetzie
Bhetzie

Reputation: 2932

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?

Upvotes: 7

Views: 7238

Answers (1)

Bean0341
Bean0341

Reputation: 1697

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

Upvotes: 2

Related Questions