Using enums in Angular with NgModel

Enums are really nice I think because you can have it to keep static data structured and easily work with it. Let us create a new enum type called LanguageTypes, it will hold some languages, we will use it in another class to set the language for that object. We will have a select element to try the enum out with the help of the ngModel property which binds the value from the enum to our object.

First of all, create a new file called language.types.ts or something similar in your Angular project under your src folder. Fill it with values you want for each enum member. Let’s go with numbers.

export enum LanguageTypes {
    English = 0,
    Swedish = 1,
  }

Okay good, we got some languages! Now, let’s create a Select form element to try it out, inside your component, have a myObject property or similar.

<div class="form-group">
  <label for="language">Language</label>
  <select [(ngModel)]="myObject.language" class="form-control" name="language" id="language">
    <option value="0">English</option>
    <option value="1">Swedish</option>
  </select>
</div>

Pretend your myObject is of a class that contains the property language like this:

import { LanguageTypes } from "./languageTypes.model";

export class MyCoolObject {
    name: string;
    language: LanguageTypes = LanguageTypes.Custom;
    constructor(name: string, lang: LanguageTypes = LanguageTypes.Swedish) {
        this.name = name;
        this.language = lang;
    }
}

Then now we are taking use of the LanguageType enum! Inside our class we have a constructor that take the default language Swedish (value 1), and we can easily change these up because enum is great in that way. We can take it a step further and replace the hardcoded values in our Select list to use the actual enum as well.

Add in your component.ts file a getter:

  public get language(): typeof LanguageTypes {
    return LanguageTypes; 
  }

Now, whenever we call the language getter property we will retrieve the enum type and can use it as normal, so replace the hard coded values 0 1 to make use of the getter instead.

<div class="form-group">
  <label for="language">Language</label>
  <select [(ngModel)]="myObject.language" class="form-control" name="language" id="language">
    <option [value]="language.English">English</option>
    <option [value]="language.Swedish">Swedish</option>
  </select>
</div>

And now our Angular app is using our own enum type.

0 0 votes
Article rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments