Switch and persist selected tab of ng2-bootstrap <tabset>, <tab> using Angular router

hgoebl picture hgoebl · Jan 18, 2017 · Viewed 7.3k times · Source

I have a component showing tabs using ng2-bootstrap tabset and tab.

Example:

<tabset>
    <tab heading="Info" [active]="tabs[0].active">
        <account-data *ngIf="tabs[0].active"></account-data>
    </tab>
    <tab heading="Users" [active]="tabs[1].active">
        <manage-users *ngIf="tabs[1].active"></manage-users>
    </tab>
    <tab heading="Billing" [active]="tabs[2].active">
        <account-billing *ngIf="tabs[2].active"></account-billing>
    </tab>
</tabset>

Note: tabs[N].active is controlled by the component and already syncs tab-changes and routes. But I have the feeling that I'm doing it the wrong way, because it's hard to manage routing inside the selected tab. Let's take the second tab, at the end of the day it should manage following sub-routes:

.../users          -> provide list of users
.../users/new      -> create new user
.../users/:id      -> show a particular user
.../users/:id/edit -> edit a particular user

It's not easy, because the component showing the tabs already uses this route:

.../:tab

It'd be way easier if there was something like this:

<tabset>
    <tab heading="Info" [routerLink]="['info']"></tab>
    <tab heading="Users" [routerLink]="['users']"></tab>
    <tab heading="Billing" [routerLink]="['billing']"></tab>
</tabset>
<router-outlet></router-outlet>

Has anybody a solution for this? This problem should be quite common...

Answer

hgoebl picture hgoebl · Jan 19, 2017

I've solved this on my own this (easy) way completely without ng2-bootstrap, just native bootstrap CSS classes, routerLink and routerLinkActive:

  <ul class="nav nav-tabs">
    <li class="nav-item">
      <a class="nav-link"
         routerLinkActive="active"
         [routerLink]="['info']">Info</a>
    </li>
    <li class="nav-item">
      <a class="nav-link"
         routerLinkActive="active"
         [routerLink]="['users']">Users</a>
    </li>

    ...

  </ul>
  <div class="tab-content">
    <div class="tab-pane active">
      <router-outlet></router-outlet>
    </div>
  </div>