Angular 4 - change color dependent on value

Use ngStyle with a method as expression. Add the following method to your component:

public getColor(balance: number): string{
   return balance > 0 ? "green" : "red";
}

And in template use it as expression:

<mat-cell *matCellDef="let row" *ngIf="row.availableBalance > 0" [ngStyle]="{'color': getColor(row.availableBalance)}"> {{row.availableBalance}}
</mat-cell>

You could use ngClass for this. https://angular.io/api/common/NgClass

<mat-table>
    <ng-container matColumnDef="availableBalance">
      <mat-header-cell *matHeaderCellDef>Available balance</mat-header-cell>
      <mat-cell *matCellDef="let row"
         [ngClass]="{
            'positive' : row.availableBalance > 0,
            'negative' : row.availableBalance < 0
         }"
      >{{row.availableBalance}}</mat-cell>
    </ng-container>
</mat-table>

In your CSS:

.positive {
    background-color: green;
}

.negative {
    background-color: red;
}

This will leave 0 unstyled.

Very simple Stackblitz example: https://stackblitz.com/edit/angular-z2hnrn

Tags:

Angular