如何在Angular 7中将CSS动态应用于按钮

时间:2019-06-14 12:55:41

标签: css angular

我是Angular的新手。

我想在单击按钮且按钮不处于活动状态时动态地将CSS(活动类)应用于按钮,并且需要删除按钮的活动类。

HTML代码

<div class="tab">
  <button (click)="onTabClick('0')">Sports</button>
  <button (click)="onTabClick('1')">News</button>
  <button (click)="onTabClick('2')">Movies</button>
</div>
<div>
  <app-sports  *ngIf="tabIndex == 0"></app-sports>
  <app-movies  *ngIf="tabIndex == 2"></app-movies>
</div>

TS文件

tabIndex = 2;

onTabClick(index){
        this.tabIndex = index;
   }

CSS

    /* Style the buttons that are used to open the tab content */
 .tab button {
   background-color: inherit;
   float: left;
   border: none;
   outline: none;
   cursor: pointer;
   padding: 14px 16px;
   transition: 0.3s;
 }

 /* Change background color of buttons on hover */
 .tab button:hover {
   background-color: #ddd;
 }

 /* Create an active/current tablink class */
 .tab button.active {
   background-color: #ccc;
 }

2 个答案:

答案 0 :(得分:1)

您可以使用 ngClass 例 [ngClass] =“ {'show':tabIndex === 2}”

这是上述情况的实现代码

HTML代码

<div class="tab">
    <button [ngClass]="{'active': tabIndex === 0}" (click)="onTabClick(0)">Transmit</button>
    <button [ngClass]="{'active': tabIndex === 1}" (click)="onTabClick(1)">Published</button>
    <button [ngClass]="{'active': tabIndex === 2}" (click)="onTabClick(2)">Bulk Transmit</button>
</div>

TS文件

tabIndex = 0;
onTabClick(index){
    this.tabIndex = index;
}

CSS文件

.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
}

.tab button:hover {
    background-color: #ddd;
}

.tab button.active {
    background-color: #ccc;
}

答案 1 :(得分:0)

您必须创建一个布尔变量才能切换

cellCache

HTML唯一方式

// public clicked = false;

<a (click)="clicked ? clicked = false : clicked = true;" [class.active]="clicked">organize</a>
// or shorter
<a (click)="clicked = !clicked" [class.active]="clicked">anchor text</a>

动态版本的另一种方法:

<li *ngFor="let n of list" [class.active]="clicked === n" 
     (click)="clicked = n">
   <a>{{n}}</a>
</li>