javascriptangularng-bootstrapng-switch

How to have different components in the ngbNav tabs?


I am using Angular and ngbNav to create tabs. The problem is that I have tab names from the API and to show them I need ngFor, but also for the content of the tab I should show different components. To implement that I have used ngSwitch.

<ul ngbNav #nav="ngbNav" class="nav-tabs">
          <li ngbNavItem *ngFor="let element of elements" [ngSwitch]="element.name">
            <a ngbNavLink>{{element.name}}</a>
            <ng-template ngbNavContent *ngSwitchCase="'Super Item'">
              <app-super-item
              ></app-super-item>
            </ng-template>

            <ng-template ngbNavContent *ngSwitchCase="'Another Item'">
              <app-another-item
              ></app-another-item>
            </ng-template>
            <ng-template ngbNavContent *ngSwitchDefault><div>Default</div></ng-template>
          </li>
        </ul>
        <div [ngbNavOutlet]="nav"></div>

I do not know how to activate the first tab in this case. Everything works but only after clicking on the tab. I would like to have the first tab active by default.


Solution

  • I would add the component as a key/value pair in the elements object. Then you could grab it in the for loop with {{element.component}}.