export enum Type {
TYPE_1 : "Apple",
TYPE_2 : "Orange",
TYPE_3 : "Banana"
}
当我记录
Type.TYPE_1
时,默认情况下会调用toString
方法。console.log(Type.TYPE_1 + " is " + Type.TYPE_1.toString());
Output => Apple is Apple
我的期待就是结果
Output : TYPE_1 is Apple
如何将键
TYPE_1
记录/获取为字符串?有办法像下面这样做吗?
export enum Type {
TYPE_1 : "Apple",
TYPE_2 : "Orange",
TYPE_3 : "Banana"
toString() {
this.key + " is " + this.toString();
<or>
this.key + " is " + this.value();
}
}
我已经在网上搜索了,我还不好。
更新
目的是在ui中显示
export enum Currency {
USD : "US Dollar",
MYR : "Malaysian Ringgit",
SGD : "Singapore Dollar",
INR : "Indian Rupee",
JPY : "Japanese Yen"
}
currencyList : Currency[]= [Currency.USD, Currency.MYR, Currency.SGD, Currency.INR, Currency.JPY];
<table>
<tr *ngFor="let currency of currencyList">
<td>
<input name="radioGroup" type="radio" [(ngModel)]="selectedType" [value]="currency">
<label>{{currency}} is {{currency.toString()}}</label>
<!--
here expectiation is Example
USD is US Dollar
MYR is Malaysian Ringgit
SGD is Singapore Dollar
....
Now I get "US Dollar is US Dollar"....
-->
</td>
</tr>
</table>
最佳答案
您可以像下面这样使用keyvalue
管道,这里是Stackblitz中的工作示例,您的enum
语法错误…请检查Enums
注:以下为角6
请检查Angular 6.1 introduces a new KeyValue Pipe
types.ts代码
export enum Type {
USD = "US Dollar",
MYR = "Malaysian Ringgit",
SGD = "Singapore Dollar",
INR = "Indian Rupee",
JPY = "Japanese Yen"
}
组件.ts代码
import { Component } from '@angular/core';
import { Type } from './types';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
states = Type;
}
component.template代码
<table>
<tr *ngFor="let state of states | keyvalue">
<td>
<input name="radioGroup" type="radio" [(ngModel)]="selectedType" [value]="currency">
<label>{{state['key'] +" is "+ state['value']}}</label>
</td>
</tr>
</table>
更新:
如果角度question