Отображение Mat-icon в зависимости от условия в цикле for
У меня есть приложение на angular-django, которое делает aPI вызов к стороннему приложению и возвращает json ответ. Я выполняю цикл обработки ответа и отображаю данные в таблице.
<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>
Здесь я хочу отобразить мат-иконку на основе значения {{item?.State}}. Например, если значение "Успешно", я хочу отобразить "значок кружочка", если "Неисправен", я хочу отобразить "значок ошибки" и т.д. Возможно ли это?
Спасибо
<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>
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. Или даже сделать это динамно с помощью пользовательского метода, который возвращает значок:
.html:
<td style="text-align:center">
<mat-icon [class]="getIconByItemState(item, true)">{{ getIconByItemState(item) }}</mat-icon>
{{item?.State}}
</td>
.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. Лучшее решение (если возможно) - сделать имя переменной State равным имени иконки:
<td style="text-align:center">
<mat-icon [class]="item?.State + '-color'">{{ item?.State }}</mat-icon>
{{item?.State}}
</td>