Skip to content

Can’t change html class when i click button in Angular components

I wanted the category I clicked on to activate. Then I added “all categories” list element and had problem. It didn’t activate when I clicked on it.

What I’ve tried:

  • I added the “clearCurrentBrand” function to clear the “currentBrand” object when I clicked on “All Brand”. I did the cleanup by defining a fake object. Then I put this object as a condition in the “getAllBrandClass” function. But it didn’t work.

I have added the codes below. I’m waiting for your help.

brand.component.html

<ul *ngIf="dataLoaded==true" class="list-group">
  <li (click)="setCurrentAllBrand()" routerLink="/cars"  [class]="getAllBrandClass()">All 
  Brands</li>

  <li [class]="getCurrentBrandClass(brand)" (click)="setCurrentBrand(brand)" 
  routerLink="/cars/brand/{{brand.brandId}}" *ngFor="let brand of brands">{{brand.brandName}} 
  </li>
</ul>

brand.component.ts

  setCurrentBrand(brand: Brand){
    this.currentBrand = brand;
  }

  setCurrentAllBrand(){
    this.currentBrand = {brandId:0, brandName:"all"}
  }

  getCurrentBrandClass(brand: Brand){
    if (brand == this.currentBrand) {
      return "list-group-item active";
    }
    else{
      return "list-group-item";
    }
  }

  getAllBrandClass(){
   if (!this.currentBrand || this.currentBrand == {brandId:0, brandName:"all"}) {
    return "list-group-item active";
   }
   else {
     return "list-group-item";
   }
  }

  clearCurrentBrand(){
    this.currentBrand = {brandId:0, brandName:''}
  }

Answer

Actually you can accomplish all that without any of the .ts code. The beauty of angular 🙂

In brand.component.ts, set currentBrand

currentBrand: any
brands: any

Then in your HTML

<ul *ngIf="dataLoaded==true" class="list-group">
  <li (click)="currentBrand=null" routerLink="/cars"  class="list-group-item" [ngClass]="{'active': !currentBrand}">All 
  Brands</li>

  <li class="list-group-item" [ngClass]="{'active': currentBrand === brand}" (click)="currentBrand = brand" 
  routerLink="/cars/brand/{{brand.brandId}}" *ngFor="let brand of brands">{{brand.brandName}} 
  </li>
</ul>