Search code examples
angularangular9mat-card

How to set active color of looped mat-cards?


I have a mat-card that is looped. How can i set the active color of the card that i clicked?

<div>
  <ng-container *ngFor="let tenant of tenantData">
  <mat-card class="card-card" (click)="onCardClick(tenant.id)">
    <mat-card-header>
      <mat-card-title>{{tenant.tenantName}}</mat-card-title>
      <mat-card-subtitle>{{tenant.abbr}}</mat-card-subtitle>
    </mat-card-header>
    <mat-card-content>
      Tenant# {{tenant.id}}
    </mat-card-content>
  </mat-card>
</ng-container>
</div>

Solution

  • Create a variable activeTenantId in *component.ts and onclick add current selected tenantId to this variable and add dynamic class

    Example

    <div>
      <ng-container *ngFor="let tenant of tenantData">
      <mat-card class="card-card" [class.active-tenant]="tenant.id === activeTenantId" (click)="onCardClick(tenant.id)">
        <mat-card-header>
          <mat-card-title>{{tenant.tenantName}}</mat-card-title>
          <mat-card-subtitle>{{tenant.abbr}}</mat-card-subtitle>
        </mat-card-header>
        <mat-card-content>
          Tenant# {{tenant.id}}
        </mat-card-content>
      </mat-card>
    </ng-container>
    </div>
    
    onCardClick(id) {
     activeTenantId = id; // <=== put your trigger here
    }