角度不根据变量更改类

时间:2020-10-21 04:18:38

标签: angular

[class.active-tab]="activeTab === 1"[ngClass]="{'active-tab': activeTab === 1 }"不会在切换activeTab变量时根据我的表达式追加类。
我已经在activeTab上初始化了变量ngOninit,并且没问题,当tab-item工作时,我的active-tab具有类ngOnint
但是,当我尝试在activeTab函数中更改toggleTab()时,ngClass[class.active-tab]不起作用。

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>

事件如果我将函数toggleTab()更改为仅返回activeTab = 2我的tab-item,则仍然错过该类
怎么了?

2 个答案:

答案 0 :(得分:1)

尝试这种逻辑可能对所有人都有帮助

.ts

<p>{{test_display.count}}</p>

.html

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;
}

.scss

<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>

您可以将此逻辑用于选项卡选项

答案 1 :(得分:0)

尝试这样

<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>

请检查现在更新的答案