[英]Mat-icon display based on condition in for loop
I have an angular-django app which makes an aPI call to a third-party application and returns json response.我有一个 angular-django 应用程序,它对第三方应用程序进行 aPI 调用并返回 json 响应。 I am looping through the response and displaying the data in a table.
我正在循环响应并在表格中显示数据。
<tr *ngFor="let item of job_list">
<td style="text-align:center">{{item?.ReleaseName}}</td>
<td style="text-align:center">{{item?.Source}}</td>
<td style="text-align:center"><mat-icon *ngIf="Successful" style="color:green;">check circle icon</mat-icon>
<mat-icon *ngIf="Faulted" style="color: red;">error icon</mat-icon>
<mat-icon *ngIf="Stopped" style="color: grey;">cancel icon</mat-icon>
{{item?.State}}
</td>
<td style="text-align:center">{{item?.StartTime | date:'dd-MM-yyyy HH:mm:ss'}}</td>
<td style="text-align:center">{{item?.EndTime | date:'dd-MM-yyyy HH:mm:ss'}}</td>
</tr>
Here, I want to display mat-icon based on {{item?.State}} value.在这里,我想根据 {{item?.State}} 值显示 mat-icon。 For example if the value is Successful, I want to display the "check circle icon", if it's "Faulted", I want to display "error icon" etc. Is this possible?
例如,如果值为Successful,我想显示“检查圆圈图标”,如果它是“Faulted”,我想显示“错误图标”等。这可能吗?
Update: Implemented ngIf but alignment is out of order:更新:已实施 ngIf 但 alignment 出现故障:
Thank you谢谢
1. You can try ngSwitch
solution but ngIf
also works: 1. 您可以尝试
ngSwitch
解决方案,但ngIf
也可以:
<td style="text-align:center">
<mat-icon *ngIf="item?.State === 'Successful'" style="color:green;">check circle icon</mat-icon>
<mat-icon *ngIf="item?.State === 'Faulted'" style="color: red;">error icon</mat-icon>
<mat-icon *ngIf="item?.State === 'Stopped'" style="color: grey;">cancel icon</mat-icon>
{{item?.State}}
</td>
2. Or even make it dinamically with a custom method that returns the icon: 2.或者甚至使用返回图标的自定义方法使其动态化:
.html: .html:
<td style="text-align:center">
<mat-icon [class]="getIconByItemState(item, true)">{{ getIconByItemState(item) }}</mat-icon>
{{item?.State}}
</td>
.ts: .ts:
getIconByItemState(item, color: boolean = false): string {
switch(item?.State) {
case 'Successful': {
return !color ? 'check circle icon' : 'green-icon';
}
case 'Faulted': {
return !color ? 'error icon' : 'red-icon';
}
case 'Stopped': {
return !color ? 'cancel icon' : 'grey-icon';
}
default: {
return 'default icon'; // ?
}
}
}
1. The best solution (if possible) is to make State variable name equals to icon name: 1.最好的解决方案(如果可能的话)是让State变量名等于图标名:
<td style="text-align:center">
<mat-icon [class]="item?.State + '-color'">{{ item?.State }}</mat-icon>
{{item?.State}}
</td>
<td style="text-align:center" [ngSwitch]="item.State">
<mat-icon **ngSwitchCase="Successful" style="color:green;">check circle icon</mat-icon>
<mat-icon **ngSwitchCase="Faulted" style="color: red;">error icon</mat-icon>
<mat-icon **ngSwitchCase="Stopped" style="color: grey;">cancel icon</mat-icon>
{{item?.State}}
</td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.