Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show different string for enums Angular 4 typescript

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.

like image 599
Red fx Avatar asked Oct 12 '17 12:10

Red fx


People also ask

Can enum be string TypeScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Can we change enum values in TypeScript?

An enum is usually selected specifically because it is immutable - i.e. you would never want the values to change as it would make your application unpredictable.

Can enums have string values?

Using string-based enums in C# is not supported and throws a compiler error. Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string.

How do you compare enums with strings?

For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.


1 Answers

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

like image 107
Lyubomir Avatar answered Oct 13 '22 23:10

Lyubomir