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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With