作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
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
如何将 key TYPE_1
记录/获取为字符串?
有没有办法像下面那样做 override method
?
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
注意:下面是Angular 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"
}
Component.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>
更新:
对于 Angular < 6,请检查 stackoverflow 之一 question
关于angular - 在 TypeScript/Angular 4+ 中将枚举键显示为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52713588/
我是一名优秀的程序员,十分优秀!