export enum AgentStatus {
available =1 ,
busy = 2,
away = 3,
offline = 0
}
を持っていませんでした
文字列を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"];
TypeScript列挙型の値をすべて取得するにはどうすればよいですか?
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);
あなたAngular2テンプレートでこれを記述する場合:
{{AgentStatus[myValue]}}
それは輸入のタイプ(それはAngularJSで、後に実行されます)へのアクセス権を持っていないので、それは失敗します。
それを動作させるために、あなたのコンポーネントが列挙型/オブジェクトへの参照を持っている必要があります、のようなもの:
export class MyComponent {
// allows you to use AgentStatus in template
AgentStatus = AgentStatus;
myValue : AgentStatus;
// ...
}
例:
import { Component } from '@angular/core';
enum AgentStatus {
available =1 ,
busy = 2,
away = 3,
offline = 0
}
例
@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;
}
}
enumsはそのような目的のために使用することができません、ok ...しかし、私はそのようにビューコンポーネントの表示タイプを指定したいと思います: 。 displayTypeの型がstringの場合、htmlテンプレートにどのように適用できますか? –
vicgoyso
文字列を持つようにenumを定義する方法 – Aravind
いいえ、今は代わりに文字列を使用することを検討しています。enumを使用できないためです。私はどのように私のHTMLテンプレートに値 "小さな"を渡すことができたか知りたいですか? – vicgoyso