How to select NgbTabset tab as active on load?

Mickey Segal picture Mickey Segal · Jul 10, 2017 · Viewed 24.9k times · Source

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?

Answer

Mickey Segal picture Mickey Segal · Jul 17, 2017

I figured out how to get this to work, but I am undecided as to whether it is a kludgy workaround or an elegant solution.

I ended up going against the advice at https://ng-bootstrap.github.io/#/components/tabs/api, which said "Use the "select" method to switch a tab programmatically". I did use activeId, with the core code being:

<ngb-tabset [activeId]="activeIdString">

[activeId] binds to a variable activeIdString, not a method as I described in the original post (using a getActiveId() method instead of a variable results in the "Expression has changed after it was checked" error message, which although it is a development mode only error, as described at https://github.com/angular/angular/issues/6005, is still a problem.)

The variable activeIdString is set when the component initializes:

  ngOnInit(): void {
    this.activeIdString = this.tabNameString[this.personService.getNextTab()];
  }

Since this code is on the component with the tabs, I record mostRecentTab on this component and convert it to nextTab on the navigation component before reaching the component with tabs, getting rid of any need to pay attention to exactly when ngOnInit executes in relation to when I record mostRecentTab.

A discussion "Cannot programmatically select tab" at https://github.com/ng-bootstrap/ng-bootstrap/issues/1016 also suggests using activeId, so I feel some confidence in disregarding the advice on https://ng-bootstrap.github.io/#/components/tabs/api to "Use the "select" method to switch a tab programmatically".