Change active tab in navbar when using router.navigate

I am using Angular 2 with Bootstrap 4. I can activate the active tab 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>

Line:

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

works well when switching to the current active tab, but when I go to the component using something like:

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

The active tab does not change. Is there a way to change the active tab when navigating as shown above?

+4
source share
1 answer

So basically you want to make your coverage in the service and call this service in order to apply your style when your URL matches a certain state. this is done using

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

plunker. , , . - , this.router.navigate(['']);,

+2

Source: https://habr.com/ru/post/1654810/


All Articles