Enums in Angular

 Enums in Angular

Enums in Angular

Enums in Angular


What can enums do for you?



Overview

Enums provide a wonderful way to help keep your code clean! They provide for less chance of making errors during code refactoring as well as make your code easier to read. But this article is not about why enums are great, it’s about how you can harness their power in a few different ways in Angular.


Basic Enums

Enums in Angular are numeric by default:


// colors.enum.ts

export enum Color {
  Blue,  // 0
  Green, // 1
  Red    // 2
}


You can also have string enums:


export enum TimeZone {
  EasternTime = 'Eastern Time',
  CentralTime = 'Central Time',
  MountainTime = 'Mountain Time',
  PacificTime = 'Pacific Time',
  AlaskaTime = 'Alaska Time',
  HawaiiAleutianTime = 'Hawaii-Aleutian Time'
}


Which you use depends upon your needs at the moment.


Enums in HTML

Once you have an enum, you will want to use it everywhere to represent the related data. But in Angular, using enums in HTML code is not as straightforward as you would think.


The Code

// colors.model.ts

import { Color } from 'colors.enum.ts';

export interface ColorsViewModel {
  Color…






Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts