How to show different string for enums Angular 4 typescript

21,473

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

Share:
21,473
Red fx
Author by

Red fx

In deep seas of Programming !

Updated on October 13, 2020

Comments

  • Red fx
    Red fx over 3 years

    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.

  • Lyubomir
    Lyubomir over 6 years
    I don't understand, this should work, see here typescriptlang.org/play/…
  • Lyubomir
    Lyubomir over 6 years
    ... and click run. What's your setup? Maybe it's just the IDE that is not configure properly. The code should work.
  • Red fx
    Red fx over 6 years
    you are right it should work as it is on the link you've shared but I dont understand really why it doesnt
  • Red fx
    Red fx over 6 years
    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.
  • Lyubomir
    Lyubomir over 6 years
    yes, typescript prior to 2.4 didn't have this feature. I've updated my answer.
  • Red fx
    Red fx over 6 years
    I'd like to have one more question please; when i stamp it as obj.foo it doesnt stamp as un deux etc. How can I achieve it? I tried several things like obj.value but I wasnt able to view it as I wanted. Do you have any suggestion?
  • Lyubomir
    Lyubomir over 6 years
    I don't know angular's bindings, neither do I know what obj is. My best guess is that you need something like obj.foo.ONE or obj.foo.TWO or obj.ONE, depends on what obj is. Post another question about that and give more information about your variables.
  • Red fx
    Red fx over 6 years
    the obj has a field of type Foo but anyways, i solved it in another way. Thanks for the help