Angular 4 - Change Color Dependent on Value

Angular 4 - Change Color Dependent on Value

I'm working with Angular 4 and I have a problem with conditional style changing. I have a table and values in it. I need the values in a column to be changed depending if the value is greater or smaller than zero. For example: if the value is 123, then its color should be green. If the value is -123, then its color should be red.

There is fragment of my code below, but it doesn't work like I'd like to:

<mat-table>
    <ng-container matColumnDef="availableBalance">
      <mat-header-cell *matHeaderCellDef>Available balance</mat-header-cell>
      <mat-cell *matCellDef="let row" *ngIf="row.availableBalance > 0" [style.color]="'red'"> {{row.availableBalance}}</mat-cell>
    </ng-container>
</mat-table>

Do you have any solutions? Thank you in advance.

2 Answers

You could use ngClass for this.

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

2

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.