角度4-根据值更改颜色 [英] Angular 4 - change color dependent on value

查看:80
本文介绍了角度4-根据值更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 4,并且在条件样式更改方面遇到问题. 我有一个表和值.我需要更改该列中的值,具体取决于该值是大于还是小于零. 例如-如果值为123,则其颜色应为绿色.如果值为-123,则其颜色应为红色.

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.

推荐答案

您可以为此使用ngClass. https://angular.io/api/common/NgClass

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>

在您的CSS中:

.positive {
    background-color: green;
}

.negative {
    background-color: red;
}

这将使0保留样式.

非常简单的Stackblitz示例: https://stackblitz.com/edit/angular-z2hnrn

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

这篇关于角度4-根据值更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆