Dilyan Georgiev
Dilyan Georgiev

Reputation: 3

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?

Upvotes: 0

Views: 4334

Answers (1)

Supamiu
Supamiu

Reputation: 8731

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.

Upvotes: 1

Related Questions