How to select NgbTabset tab as active on load?

Viewed 32355

The "Select an active tab by id" example at https://ng-bootstrap.github.io/#/components/tabs shows how to use a DOM button to programmatically select an Angular Bootstrap tab to be active. But how do you set a tab to be active from within the TypeScript code - for example by referencing some persistent state of what tab was most recently open on this view using a service that stored the state?

The activeId documentation on that page explains how to hard-code a tab to be active, but I need to set the tab choice programmatically. I can set the tab using [activeId] = getActiveId() (where getActiveId() accesses a service in which I can store the tab value), but that gets into all sorts of issues with when the activeId is set, which is presumably why the documentation says "Use the "select" method to switch a tab programmatically".

Following this direction I tried using select on the ngb-tabset and using the html onload event to solve this in the DOM, but was unclear where to place onload and I couldn't get this to work.

I tried using ngOnInit in the TypeScript to set the DOM state but couldn't figure out how to refer to the ngb-tabset.

What is a good way to coordinate between the TypeScript and the DOM to select NgbTabset tab as active on load?

5 Answers

Somehow those answers didnt work, so I found another solution. An easier one. I hope it helps someone. Just follow these steps:

1. Give your tabset a 'tabset' identifier:

<ngb-tabset #tabset="ngbTabset"> many tabs... </ngb-tabset>

2. Give every <tab> in your <tabset> an unique id

<ngb-tab id="tab1"> Tab 1 </ngb-tab>
<ngb-tab id="tab2"> Tab 2 </ngb-tab>
<ngb-tab id="tab3"> Tab 3 </ngb-tab>

3. Declare a @ViewChild for your tabset

@ViewChild('tabset')
tabset: any;

4. Set active tab inside ngAfterViewInit (not ngOnInit, that's too early!)

this.tabset.select('tab3');

Works perfectly for me. Sorry for strange formatting, Stack Overflow doesnt work properly sometimes.

According to docs, you need to use select method. To do that, first add identificator for tabset in your view html file:

<ngb-tabset #tabset="ngbTabset">

In your .ts file declare your ViewChild:

@ViewChild('tabset') tabset;

And then just use method this way:

this.tabset.select(YOUR_TAB_ID_HERE);

PS: Althought @Mickey Segal solution may work in most cases, in my projects i saw, that sometimes it doesn't work, so i suggest to use documented way of changing active tab.

<tabset class="tabset" #tabset id="tabset">
<tab></tab>
<tab></tab>
</tabset>

Declare tab viewchild

@ViewChild('tabset', { static: true }) tabset: any;

Then on changeEvent or ngOnInit method you can make any tab as active by its index no like

this.tabset.tabs[indexNo].active = true

Related