
This is a short guide on using Enums in an Angular application.
Below you will see how to:
- Reference an Enum in your
component.html
templates - Itterate over an enum using
*ngFor
and thekeyvalue
pipe - Conditionally show content using an Enum and
*ngIf
- Get all the values of an enum as an
Array<sting>
Intro
You can skip the next block of text if you just want to get the actual details (I respect that)
I love using Enums in TypeScript as I am a terrible developer with a terrible memory and let my editor's auto complete do 80% of my job. Enums let you avoid using strings and having to remember what string values you used. They also allow you to lock down the values a property can be, so that a user can't just submit any value they want. So if you aren't using them, start using them, and if you are already using them, use them more, use them to a fault. Be the Enums you want to see in the world.
Example use of an enum for those unfamiliar
// This is our PropertyType enum// We give each value a string value otherwise PropertyType.House would return 0, Property.Apartment would return 1, and so onenumPropertyType{House='House',Apartment='Apartment',Flat='Flat',Studio='Studio'}// Our class which has a 'type' property.// We want to lock type down to a set of predefined valuesclassProperty{constructor(publicmonthlyPrice:number,publictype:PropertyType){}}// Creates a property successfullyconstproperty=newProperty(1250,PropertyType.Apartment);// Will display an error from our linter and in the Angular CLIconstproperty=newProperty(1250,PropertyType.RANDOM_VALUE);
Enums can be used in your Angular templates. This is handy for situations like avoiding a hard coded set of values for a dropdown menu or displaying different content based on your component state. In my opinion, this pairs very nicely with reactive forms.
To make an Enum accessible in your Angular template you need to first store it in a variable in our component.ts file. For this example, we will create a simple reactive form to create aProperty
// Declaring our Enum. The Enum could also be imported from another file if neededenumPropertyType{House='House',Apartment='Apartment',Flat='Flat',Studio='Studio'}@Component({selector:'app-property-component',templateUrl:'./property.component.html'})exportclassPropertyComponent{// Make a variable reference to our EnumePropertyType=PropertyType;// Build our formform:FormGroup;type:FormControl;price:FormControl;// This is only here to make the form look more l3g1tconstructor(privateformBuilder:FormBuilder){this.form=this.formBuilder.group({type:[null,[Validators.required]],price:[0,[Validators.required]]});this.type=this.form.controls.typeasFormControl;this.price=this.form.controls.priceasFormControl;}}
Then in ourproperty.html
template, we can utilize our Enum as follows. We will use thekeyvalue
pipe. This takes ourPropertyType
enum (referenced asePropertyType
) and turns it into aKeyValue
array, which we can iterate over with*ngFor
. As we declared ourPropertyType
with a string value (ie.Apartment = 'Apartment'
) theKeyValue.key
andKeyValue.value
will both contain the string value of the enum so we can use either.
We then can use our Enum as part of an*ngIf
to conditionally display a message.
<form[formGroup]="form"><!-- Property type form control --><labelfor="propertyType">Property Type</label><selectid="propertyType"[formControl]="type"><option[ngValue]="null">Select one...</option><option*ngFor="let type of ePropertyType | keyvalue"[ngValue]="type.value">{{type.value}}</option></select><!-- Property price form control --><labelfor="propertyPrice">Property Price</label><inputid="propertyPrice"class="form-control"type="number"[formControl]="price"placeholder="Street..."></form><!-- Conditionally display a message if a certain PropertyType is selected (or not selected) --><ng-container*ngIf="type.value !== ePropertyType.House">Wouldn't you prefer a nice garden?</ng-container>
How to get an array of strings from an Enum
A nice little trick to get an array of strings(string[]
, orArray<string>
if you're a cool boi like myself) from an Enum is to use useObject.keys
andArray.filter
// Declare your enumenumPropertyType{House='House',Apartment='Apartment',Flat='Flat',Studio='Studio'}/* Get an array of keys, filtering out number values* as the enum object itself is as follows* { 0: 'House', 1: 'Apartment' ...}*/constpropertyType:Array<string>=Object.keys(PropertyType).filter(key=>isNaN(+key));
Conclusion
Enums are lit, use them more often.
Top comments(3)

Nice article!
I Found this when searching for "using enums in Angular templates" as I was getting a type error when doing an AOT build:
Argument of type 'string' is not assignable to parameter of type 'MyEnumName'.
I did indeed need to convert my enum to an array of strings in order to compare against another string value, which I did usingObject.values()
rather thanObject.keys()
as mentioned in your article:
public myArray = Object.values(MyEnumName).map(item => String(item));

Pretty sure.values
and.keys
will do the same thing if you have your enum declare with a string value as follows
enum PropertyType { House = 'House'}
I assume you just have your enum declared like the below
enum PropertyType { House = 'House'}
For further actions, you may consider blocking this person and/orreporting abuse