How to apply CSS to button dynamically in Angular 7

Viewed 5386

I'm very new to Angular.

I want to apply CSS (active class) to a button dynamically when it is clicked and the button is not active and need to remove the active class to the button.

HTML code

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

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 Answers

You must create a bool variable to toggle

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

The HTML only way

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

Another way for dynamic verions:

// component
toggleReply: any = {};

// view
<a (click)='toggleReply[i] = !toggleReply[i]'>
    <ng-container *ngIf="!toggleReply[i]">reply</ng-container>
    <ng-container *ngIf="toggleReply[i]">close</ng-container>
</a>

You can use ngClass Example [ngClass]="{'show': tabIndex === 2}"

Here the implemented code for the above scenario

HTML CODE

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

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

CSS FILE

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