我有6列,即姓名,电子邮件,电话,公司,status_1和status_2。
status_1有两个选项,即“ .1”或“ 0” status_2也有两个选项,即“ 1”或“ 0”
我的要求:我需要更改行的颜色
逻辑:
if(status_1 is "1" -> change to red)
else if (status_2 is "1" -> change to green)
else if (status_1 and status_2 is "1" -> give priority to status_1)
Mycode:
<div>
<mat-table [dataSource]="dataSource">
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="email">
<mat-header-cell *matHeaderCellDef> E-Mail </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.email}} </mat-cell>
</ng-container>
<ng-container matColumnDef="phone">
<mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.phone}} </mat-cell>
</ng-container>
<ng-container matColumnDef="company">
<mat-header-cell *matHeaderCellDef> Company </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.company.name}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
我将显示4列,并且应根据状态更改行的颜色
请帮助我
谢谢。
答案 0 :(得分:3)
将mat-row
更改为
<mat-row *matRowDef="let row; columns: displayedColumns;" [ngStyle]="{'background-color': getRowColor(row)}"></mat-row>
getRowColor(row){
if (row.status_1 === '1') {
return "red";
} else if (row.status_2 === '1') {
return "green";
}
}
答案 1 :(得分:1)
您需要使用[ngStyle]
来指定您的条件。假设您给出的整个清单都是您的行,则将指令添加到最外面的<div>
中,如下所示:
<div [ngStyle]="{ 'background-color': status_1 === '1' ? 'red' : (status_2 === '1' ? 'green' : 'auto') }">
<mat-table [dataSource]="dataSource">
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="email">
<mat-header-cell *matHeaderCellDef> E-Mail </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.email}} </mat-cell>
</ng-container>
<ng-container matColumnDef="phone">
<mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.phone}} </mat-cell>
</ng-container>
<ng-container matColumnDef="company">
<mat-header-cell *matHeaderCellDef> Company </mat-header-cell>
<mat-cell *matCellDef="let user"> {{user.company.name}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
我认为表达式应该在函数中,这将更易于阅读且易于维护。给定
getColor() {
if (status_1 === '1') {
return 'red';
} else if (status_2 === '1') {
return 'green';
}
}
您可以将<div>
更改为使用:
<div [ngStyle]="{ 'background-color': getColor() }">