Map your TypeScript Enums
ES6 introduced Map that is a key/value data structure that should be very familiar to Java and .NET developers. In JavaScript we always had a object literal that quite similar to Map except of one big limitation. Object literal requires to have key as a string and Map supports any object. Let’s try to see how we can use Enum with Map in Angular 2 templates.
Define enum
Let say we have typescript enum.
enum Fruits {
APPLE,
ORANGES
}
Typescript transpilers the enum values to integers. It is easy to check with typescript playground at https://www.typescriptlang.org/play/index.html
var Fruits;
(function (Fruits) {
Fruits[Fruits["APPLE"] = 0] = "APPLE";
Fruits[Fruits["ORANGES"] = 1] = "ORANGES";
})(Fruits || (Fruits = {}));
Define Map
Using Enum as key we can create ES6 Map that maps enum key to meaningful message.
const FruitsName = new Map<number, string>([
[Fruits.APPLE, 'Yummy Apples'],
[Fruits.ORANGES, 'Big Oranges']
]);
Angular component Template
Now you can use enum and Map in the template and have pretty readable code.
@Component({
selector: 'my-app',
template: `
<ul>
<li (click)="selected(fruits.APPLE)">
{{fruitsName.get(fruits.APPLE)}}
</li>
<li (click)="selected(fruits.ORANGES)">
{{fruitsName.get(fruits.ORANGES)}}
</li>
</ul>
`
})
export class App {
fruitsName;
fruits; constructor() {
this.fruitsName = FruitsName;
this.fruits = Fruits;
} selected(fruit) {
console.log(fruit);
}
}