6

I have a string based enum. Without changing the enum class, I need to display different strings on my modal. My obj contains the enum. My code is as follows:

ENUM:

  export enum FooEnum {
        ONE,
        TWO,
        THREE
    }

HTML:

<select class="form-control"
                    type="text"
                    id="foo"
                    [(ngModel)]="obj.foo"
                    required
                    name="foo"
                    #foo="ngModel">
              <option *ngFor="let foo of fooToList()" [ngValue]="foo">{{foo}}</option>
            </select>

TypeScript:

  fooToList(): Array<string> {
    const keys = Object.keys(FooEnum);
    return keys.slice(keys.length / 2);
  }

I would like to view ONE as Un, TWO as Deux etc. Could you help me pretty please ?

Note: I included angular 2 also because 2 and 4 are highly similar.

1 Answer 1

10

You can initialise enums with values too such as

enum FooEnum { 
  ONE = 'Un',
  TWO = 'Deux',
  ... etc
}

See documentation.

Note: This was introduced in TypeScript 2.4

Sign up to request clarification or add additional context in comments.

8 Comments

I don't understand, this should work, see here typescriptlang.org/play/…
... and click run. What's your setup? Maybe it's just the IDE that is not configure properly. The code should work.
you are right it should work as it is on the link you've shared but I dont understand really why it doesnt
I have seen that the version of typescript used in the project is older that they have put this feature; I will be trying to update the project.
yes, typescript prior to 2.4 didn't have this feature. I've updated my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.