Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Working with Enums in Angular components
Shane McGowan
Shane McGowan

Posted on • Edited on

     

Working with Enums in Angular components

This is a short guide on using Enums in an Angular application.
Below you will see how to:

  • Reference an Enum in yourcomponent.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 anArray<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);
Enter fullscreen modeExit fullscreen mode

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;}}
Enter fullscreen modeExit fullscreen mode

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>
Enter fullscreen modeExit fullscreen mode

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));
Enter fullscreen modeExit fullscreen mode

Conclusion

Enums are lit, use them more often.

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
_builtbyjay profile image
Jay Vincent
Website maker, booty shaker
  • Location
    London
  • Work
    Frontend developer at Housekeep
  • Joined

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'.
Enter fullscreen modeExit fullscreen mode

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));
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
shane profile image
Shane McGowan
Burned out web dev
• Edited on• Edited

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'}
Enter fullscreen modeExit fullscreen mode

I assume you just have your enum declared like the below

enum PropertyType {  House = 'House'}
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
daviddalbusco profile image
David Dal Busco
  • Location
    Zürich
  • Joined

Thanks for the share Shane, the Form and enum example is something I was looking for 👍

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Burned out web dev
  • Location
    Ireland
  • Joined

More fromShane McGowan

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp