Angular – enums and switch case in templates

Angular – enums and switch case in templates

Although TypeScript has support for enums, Angular’s templates can access only fields …. by the related component. I will present two ways of accessing enums in templates.

Assumptions

We store enum in a model, outside of the component:

TypeScript
model.ts

We also have a component that inputs the Item:

TypeScript
item.component.ts

Way 1 – ngIf

Both solutions require import of the enum type State and allowing template access it by creating a field equal to the enum – lines 2 and 14 below:

My related project

Timeline Creator

Create and export timeline graphs using an online tool

TypeScript
item.component.ts

Although it may seem strange and confusing (State = State), it’s required to allow the template access an enum type. In the template, we check the value of state as we would do in the component code.

I added optional chaining for cases when item will be undefined.

Way 2 – ngSwitch

Another solution utilizes ngSwitch in case multiple variants have to be covered, and only one of them should be executed:

TypeScript
item.component.ts

It works similarly as the switch keyword in JavaScript. All switch cases are exclusive and only the first one matching the condition will be executed.

5 1 vote
Article Rating

Want more?

Share!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x