Sunstrike527
Sunstrike527

Reputation: 607

Angular do not change the class depending on variable

[class.active-tab]="activeTab === 1" and [ngClass]="{'active-tab': activeTab === 1 }" do not append class depending on my expression when I toggle the activeTab variable.
I have initialized variable activeTab on ngOninit and it is ok , my tab-item has class active-tab when ngOnint works.
But when I try to change activeTab in my toggleTab() function , ngClass and [class.active-tab] do not work.

main-page.component.ts

ngOnInit(): void {
    this.activeTab = 1; // works perfect
  }
 toggleTabs(id) {
    this.activeTab = id + 1;
    console.log(this.activeTab) // gives 1,2,3 depending on clicked tab
  }

main-page.component.html

 <div class="tabs">
   <div *ngFor="let tab of tabs; let i = index" (click)="toggleTabs(i)" // here I change tab
      [ngClass]="[tab.isActive ? 'active' : '' , tab.type ? tab.type : '']" class="tab">
                        {{tab.title}}
   </div>
 </div>
 <div class="tab-content">
    <div [class.active-tab]="activeTab === 1" class="tab-item green">TAB CONTENT 1</div>
    <div [class.active-tab]="activeTab === 2" class="tab-item green">TAB CONTENT 2</div>
    <div [class.active-tab]="activeTab === 3" class="tab-item green">TAB CONTENT 3</div>
 </div>

Event If I change function toggleTab() to return only activeTab = 2 my tab-item anyway miss the class
What is wrong ?

Upvotes: 1

Views: 244

Answers (2)

Prakash Harvani
Prakash Harvani

Reputation: 1041

try Like this,

<div class="tab-content">
  
<div [ngClass]="{ 'active-tab': activeTab == '1' }" class="tab">TAB CONTENT 1</div>
<div [ngClass]="{ 'active-tab': activeTab == '2' }" class="tab">TAB CONTENT 2</div>
<div [ngClass]="{ 'active-tab': activeTab == '3' }" class="tab">TAB CONTENT 3</div>

 </div>

Please check now updated answer

Upvotes: 0

Dako patel
Dako patel

Reputation: 920

try this logic may it will helpful for all

.ts

public tabs = {
list: [
  {
    tab: 'all',
    label: 'All'
  },
  {
    tab: 'home',
    label: 'Home Page'
  }
 ],
activeTab: 'all',
}

ngOnInit() {
   this.changeTab('all');
}

changeTab(tab: string) {
    this.tabs.activeTab = tab;
}

.html

<div class="tabs">
        <div class="tab" *ngFor="let tab of tabs.list; let i = index" (click)="changeTab(tab.tab)"
            [ngClass]="tabs.activeTab == tab.tab? 'active' : ''"> {{tab.label}}
        </div>
 </div>
    <div>
       {{this.tabs.activeTab}}
    </div>

.scss

.tab {
        cursor: pointer;
        padding: 15px 20px;
        font-weight: 400;
        color: #b7b7b7;
        &.active {
            border-bottom: 1px solid $brand-color;
            margin-bottom: -1px;
            color: $brand-color;
        }
}

you can use this logic for tab option

Upvotes: 1

Related Questions