How to programmatically select a angular bootstrap nav tab from a component class

Viewed 2469

Hi how can I obtain a reference to a ngbNav ng-bootstrap component in my component class so I can select some tab programmatically? This doesnt work:

@ViewChild('nav') nav? : ElementRef<NgbNav>;

In my html template I have:

<ul ngbNav #nav="ngbNav" [(activeId)]="active" (navChange)="onNavChange($event)" class="nav-tabs">
1 Answers

Your approach seems to work for me - I just needed to add a method to select the tab; you can call this.nav.select(index); to select the tab you require programatically (tabs indexes start from 1 rather than 0).

I've created a demo here - click the button below the tabs to select the third tab. The code is:

HTML

<button (click)="selectTab()">Select Tab 3</button>

TypeScript

@ViewChild("nav") // Get a reference to the ngbNav
nav;

selectTab() {
    // Programatically select the third tab
    this.nav.select(3);
}
Related