您好,我正在尝试使用带有枚举的条件类。我之前在 ngSwitchCase
中使用过 html 中的枚举,并且遇到了与现在相同的错误。当我添加一个名为该枚举的属性并将其分配给该枚举时,它将起作用。
工作示例:
<ng-container *ngFor="let column of columns" [ngSwitch]="column.dataType">
<td *ngSwitchCase="DataType.Text">{{getPropertyValue(row,column.propertyName)}}</td>
<td *ngSwitchCase="DataType.Date">date</td>
<td *ngSwitchCase="DataType.Number">number</td>
<td *ngSwitchDefault>default</td>
</ng-container>
ts
private DataType = DataType;
不工作:
<span *ngClass="(column.sortType === SortType.Ascending)? 'privilege-grid-sortasc': (column.sortType === SortType.Descending)?'privilege-grid-sortdesc':'privilege-grid-sortnone'"></span>
我也尝试过 [ngClass] ="{'class-name': var === enum,...}"
ts
private SortType = SortType;
错误信息:
Cannot read property 'Ascending' of undefined
最佳答案
我在这里找到了一个非常好的教程:https://coryrylan.com/blog/angular-tips-template-binding-with-static-types
总的来说语法是 [ngClass] ="{'class-name': var === enum}":
@Component({
selector: 'app-message',
template: `
<div class="message" [ngClass]="{
'message--error': messageTypes.Error === type,
'message--success': messageTypes.Success === type,
'message--warning': messageTypes.Warning === type
}">
<ng-content></ng-content>
</div>
`
})
export class MessageComponent implements OnInit {
@Input() type = MessageTypes.Default;
private messageTypes = MessageTypes; //very important to declare here
constructor() { }
ngOnInit() { }
}
关于html - 带有 ngClass 的 Angular 2 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46324673/