此模板中的[ngClass]太长。有简单的方法吗?谢谢。
<ng-container matColumnDef="ThisConsult.Status">
<th mat-header-cell *matHeaderCellDef mat-sort-header [ngClass]="'headerStyle'">Status</th>
<td mat-cell *matCellDef="let element">
<div [ngClass]="{'seahawk': element.ThisConsult.Status==='PENDING', 'blue': element.ThisConsult.Status==='ACTIVE',
'blackOnWhite': element.ThisConsult.Status==='DISCONTINUED', 'grayOnWhite': element.ThisConsult.Status=='COMPLETE',
'bloody': element.ThisConsult.Status==='CANCELLED'}">
{{element.ThisConsult.Status}}
</div>
</td>
</ng-container>
答案 0 :(得分:1)
您可以在Component上创建一个函数来调用模板,以避免ngClass上的条件列表过多
示例:
UserComponent
@Component({...})
export class UserComponent {
constructor() {}
assignClassByStatus(element: any): string {
const classes = [
{ name: 'seahawk', type: 'PENDING' },
{ name: 'blue', type: 'ACTIVE' },
{ name: 'blackOnWhite', type: 'COMPLETE' },
{ name: 'grayOnWhite', type: 'DISCONTINUED' },
{ name: 'bloody', type: 'CANCELLED' },
];
const className = classes.find(({ type }) => type === element).name;
return className;
}
}
用户模板
...
<td mat-cell *matCellDef="let element">
<div [ngClass]="assignClassByStatus(element)">{{element.ThisConsult.Status}}</div>
</td>
答案 1 :(得分:1)
您可以简单地将对象用作字典:
component.ts
class SomeComponent {
statuses = {
PENDING: 'seahawk',
ACTIVE: 'blue',
DISCONTINUED: 'blackOnWhite',
COMPLETE: 'grayOnWhite',
CANCELLED: 'bloody'
}
...
template.html
[ngClass]="statuses[element.ThisConsult.Status]"