Hello I am trying to use a conditional class with an enum. I have used enums in html before with ngSwitchCase
and have the same error that I'm getting now. When I would add a property called that enum and assign it to that enum it would work.
working example:
<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;
not working:
<span *ngClass="(column.sortType === SortType.Ascending)? 'privilege-grid-sortasc': (column.sortType === SortType.Descending)?'privilege-grid-sortdesc':'privilege-grid-sortnone'"></span>
I also have tried [ngClass] ="{'class-name': var === enum,...}"
ts
private SortType = SortType;
error message:
Cannot read property 'Ascending' of undefined
I found a really good tutorial here : https://coryrylan.com/blog/angular-tips-template-binding-with-static-types
in summary the syntaxe is [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() { }
}
I think your problem must lie somewhere else. I recreated your scenario using the [ngClass] binding with an enum and it works fine for me:
[ngClass] ="{'class-name': var === enum,...}"
Is your template in the second case on a separate .html file and not in the first case? I've had problems where a private variable on my component file can't be read by the template file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.