角度4 - 根据值改变颜色

big*_*ter 8 angular

我正在使用Angular 4,我遇到了条件样式更改的问题.我有一张桌子和价值观.我需要根据值是大于还是小于零来更改列中的值.例如 - 如果值为123,则其颜色应为绿色.如果值为-123,则其颜色应为红色.

下面是我的代码的片段,但它不像我想的那样工作:

<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>
Run Code Online (Sandbox Code Playgroud)

你有什么解决办法.先感谢您.

mah*_*val 21

您可以使用ngClass.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>
Run Code Online (Sandbox Code Playgroud)

在你的CSS中:

.positive {
    background-color: green;
}

.negative {
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

这将使0没有风格.


小智 6

将ngStyle与方法一起用作表达式.将以下方法添加到组件:

public getColor(balance: number): string{
   return balance > 0 ? "green" : "red";
}
Run Code Online (Sandbox Code Playgroud)

在模板中使用它作为表达式:

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