Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 513
hgoebl Avatar asked Dec 06 '25 06:12

hgoebl


1 Answers

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>
like image 121
hgoebl Avatar answered Dec 07 '25 22:12

hgoebl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!