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
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
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.
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 :).