Angular – enums and switch case in templates
Although TypeScript has support for enum
s, Angular’s templates can access only fields …. by the related component. I will present two ways of accessing enums in templates.
Table of contents
Assumptions
We store enum in a model, outside of the component:
We also have a component that inputs the Item
:
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.
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:
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.
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!