Dilyan Georgiev Dilyan Georgiev - 2 months ago 30
JSON Question

Typescript enum stored in json

I'm working with Typescript and Angular 2 and
I want to create enum dynamically from some json data.
For instance I want to set enum for a dropdown menu and want to get the options from a json. How to do this?

Answer

In Typescript, enums are transpiled as JS arrays (see Enums in TypeScript: what is the JavaScript code doing?).

So, if you want to dynamically load an enum, you just have to load an array.

But if your goal is to create a select out of this enum, you should definetly deserialize your json and pass it to a component with an embedded select, creating options from your object using an *ngFor.

The easiest way would be to format your JSON this way:

{
   "selectData":[
                     { 
                      "key":"foo", 
                      "value":"bar"
                     }
                ]
}

This way you can load your json and iterate on selectData array, using key and value values to create your select.