export enum AgentStatus {
available =1 ,
busy = 2,
away = 3,
offline = 0
}
How do you convert a string to an enum in TypeScript?
var value = AgentStatus["offline"]; // so value is now 0
// You can also use this, which only gives IDE hints, no runtime benefit
var value: AgentStatus = AgentStatus["offline"];
How to get all the values of a TypeScript enum type?
var options : string[] = Object.keys(AgentStatus);
// The options list has the numeric keys, followed by the string keys
// So, the first half is numeric, the 2nd half is strings
options = options.slice(options.length / 2);
If you write this in your Angular2 template:
{{AgentStatus[myValue]}}
It will fail, because it doesn’t have access to imported types (it gets executed later by AngularJS).
To make it work, your component will need to have a reference to the enum type / object, something like:
export class MyComponent {
// allows you to use AgentStatus in template
AgentStatus = AgentStatus;
myValue : AgentStatus;
// ...
}
example:
import { Component } from '@angular/core';
enum AgentStatus {
available =1 ,
busy = 2,
away = 3,
offline = 0
}
example
@Component({
selector: 'my-app',
template: `
<h1>Choose Value</h1>
<select (change)="parseValue($event.target.value)">
<option>--select--</option>
<option *ngFor="let name of options"
[value]="name">{{name}}</option>
</select>
<h1 [hidden]="myValue == null">
You entered {{AgentStatus[myValue]}}
<br>
You are {{isOffline ? "offline" : "not offline"}}.
</h1>`
})
export class AppComponent {
options : string[];
myValue: AgentStatus;
AgentStatus : typeof AgentStatus = AgentStatus;
isOffline : bool;
ngOnInit() {
var x = AgentStatus;
var options = Object.keys(AgentStatus);
this.options = options.slice(options.length / 2);
}
parseValue(value : string) {
this.myValue = AgentStatus[value];
this.isOffline = this.myValue == AgentStatus.offline;
}
}