htmlangularangular-materialangular-material-5

How to change the color of the mat icon of a specific row in angular material table when clicked?


I have a mat-table with columns: Name and Plot.

The html, .ts and .css code that i have tried is as below:

.html

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>Name</th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- dataset Column -->
  <ng-container matColumnDef="actions">
    <th mat-header-cell *matHeaderCellDef>Plot</th>
    <td mat-cell *matCellDef="let element">
      <button mat-icon-button aria-label="Example icon button with a heart icon">
        <mat-icon color=accent (click)="onSignalPreview(element); colorchange(element)">
          <i class="fas fa-heart" [ngClass]="{'active': isActive}">preview</i>
        </mat-icon>
      </button>
    </td>
  </ng-container>

.ts

public isActive:boolean = false;
  colorchange(signal) {
    this.isActive = !this.isActive;
  }

.css

.fa-heart {
  color: #ccc;
}

.fa-heart.active {
  color: deeppink;
}

Currently, color of mat-icons in all the rows gets changed if i click on the icon of any row and if i click the second time, color of all the rows gets changed again.

I want to change the color of the mat-icon of the specific row which i click and not the mat-icon color of all the rows. And also change the color back to original color if i click on the same row icon once again.

How can i achieve this ?


Solution

  • in your ts file try

    colorchange(signal) {
        signal.isActive = !signal.isActive;
      }
    

    and in your component html file replace

    [ngClass]="{'active': isActive}"
    

    with

    [ngClass]="{'active': element.isActive}"
    

    for reference check this example on click of symbol data it will change color of symbol of specific row.