skip to Main Content

I am using twitter bootstrap tabs and I want to keep track of the active class that is applied to the li tag as the user toggles different tabs. I am keeping track of class attribute because I want to activate tabs through my own custom buttons by changing class attribute to activate from the code. I am using the following code to achieve this:

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

@Component({
  selector: 'app',
  template: `
  <div class="container-fluid" >
    <ul class="nav nav-tabs" >
      <li *ngFor="#tab of tabs"  [(class)]="tab.class" ><a href="#{{tab.id}}" data-toggle="tab" >{{tab.id}}</a></li>
    </ul>
    <div class="tab-content">
      <div *ngFor="#tab of tabs" [(class)]="tab.contentClass" [id]="tab.id" >{{tab.id}} content goes here.</div>
    </div>
  </div>
  <button (click)="openTab('tab1')" >Tab 1 Button</button>
  <button (click)="openTab('tab2')" >Tab 2 Button</button>
  `
})
class MainApp{
  public tabs = [
    {class: "active", id: "tab1", contentClass:"tab-pane active"},
    {class: "", id: "tab2", contentClass:"tab-pane"}
  ]

  openTab(id){
    var tabToActivate;
    for(var i=0;i<this.tabs.length;i++){
      if(this.tabs[i].id == id)
        tabToActivate = this.tabs[i];
      this.tabs[i].class = "";
      this.tabs[i].contentClass = "tab-pane";
    }

    tabToActivate.class = "active";
    tabToActivate.contentClass = "tab-pane active";
  }
}
bootstrap(MainApp);

but it seems that as I toggle through different tabs the binding gets break or something and the customized tab buttons doesn’t work for a moment. Why is this happening?

I re-produced the problem on plunkr here

click tab2

click Tab Button 1 – doesn’t work.

Any thoughts?

2

Answers


  1. I would use ngClass instead:

    <li *ngFor="#tab of tabs" 
          [ngClass]="{active: tab.active}">...</li>
    

    The active property must be true or false according if the tab i’s active or not.

    See this link: https://v2.angular.io/docs/js/latest/api/common/index/NgClass-directive.html.

    Login or Signup to reply.
  2. I found some logic error in your plunker. Now, check below code and working plunker (according to your way of coding).

    working demo

    <ul class="nav nav-tabs" >
          <li *ngFor="#tab of tabs"  (click)="openTab(tab.id)" [(class)]="tab.class" ><a href="#{{tab.id}}" data-toggle="tab" >{{tab.id}}. {{tab.class}}</a></li>
    </ul>
    
    openTab(id){        
        for(var i=0;i<this.tabs.length;i++){
          console.log('started' + id);
          if(this.tabs[i].id != id)
          {   
            this.tabs[i].class = ""; 
            this.tabs[i].contentClass = "tab-pane";
          }
          else
          {
            this.tabs[i].class = "active"; 
            this.tabs[i].contentClass = "tab-pane active";
          }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search