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:

Note: I'll soon be sharing short, practical tips on Angular — a good way to pick up something new if you're interested.

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.

Read next

4 4 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
سورة البقرة مكررة
سورة البقرة مكررة
1 year ago

Your writing is a true testament to your expertise and dedication to your craft. I’m continually impressed by the depth of your knowledge and the clarity of your explanations. Keep up the phenomenal work!

1
0
Would love your thoughts, please comment.x
()
x