2

I am having an issue with joining enum with SELECT from HTML. My enum structure looks as follows:

enum Color {
    Green,
    Red,
    Blue
}

I would like to somehow bind this enum to the html select tag, using angular. Any ideas?

Thanks
uksz

uksz
  • 18,239
  • 30
  • 94
  • 161

2 Answers2

3

When your enum is compiled to JavaScript, it will become the following object. You can see the equivalent JavaScript here at TypeScript playground.

{
   0: "Green"
   1: "Red"
   2: "Blue"
   "Blue": 2
   "Green": 0
   "Red": 1   
}

Now as you can see, if you were to bind this with a <select> you will get both the numeric and non-numeric items. Assuming you only want non numeric items to show up in the list, you will need to filter it.

Obaid
  • 1,407
  • 19
  • 36
1

I landed up with this when I had same question. I figured this out after some research and felt to share it here.

If we don't need the int value of the enum, then we can write the enum structure like below. Ref from

enum Color {
  Green = <any>"Green",
  Red = <any>"Red",
  Blue = <any>"Blue"
}

This will be converted to

var Color;
(function(Color) {
  Color[Color["Green"] = "Green"] = "Green";
  Color[Color["Red"] = "Red"] = "Red";
  Color[Color["Blue"] = "Blue"] = "Blue";
})(Color || (Color = {}));

This is equivalent to

{
  "Green": "Green"
  "Red": "Red"
  "Blue": "Blue"
}

We need to iterate through this and fill an array with this properties and use the array.

var colors: string[] = [];
for (var item in Color) {
    if (Color.hasOwnProperty(item)) {
        this.colors.push(item);
    }
 }

The colors array can be used like regular array to populate select values.

<select ng-model="colorModel">
    <option ng-repeat="option in vm.colors" value="{{option}}" >{{option}}</option>
 </select>

If you want to use int values, we can use the regular Enum and filter the values to fill the array to use in HTML. refer here for more details on how to filter.

Hope this helps some one who lands here :).

user5664615
  • 400
  • 1
  • 10
  • 17
Vinay
  • 87
  • 1
  • 7
  • nice answer, but this still appears to show values as well as keys in the enum. To see this, change the "string" value of "green" to "greener" and you'll end up with the colors array being 4 long. – lowcrawler Jan 24 '17 at 19:26
  • @lowcrawler, Totally understood. When we change the value of enum it'll become a property and when we check for hasOwnProperty() it;s returning both value and key. Why do you need to change it to "greener"?. This was mainly for the workaround for the basic enum. – Vinay Feb 02 '17 at 00:57
  • Basically, this doesn't work unless the variable name and the string value are the exact same. That's fine, it's just not useful in a 'dictionary' type situation... – lowcrawler Feb 03 '17 at 10:55