在 TypeScript / Angular 4+ 中将枚举键显示为字符串

Zaw*_* oo 3 typescript typescript2.0 angular

export enum Type {
    TYPE_1 : "Apple",
    TYPE_2 : "Orange",
    TYPE_3 : "Banana"
}
Run Code Online (Sandbox Code Playgroud)

当我登录时Type.TYPE_1toString默认调用方法。

console.log(Type.TYPE_1 + " is " + Type.TYPE_1.toString());

Output => Apple is Apple
Run Code Online (Sandbox Code Playgroud)

我的期望是结果就像

Output : TYPE_1 is Apple
Run Code Online (Sandbox Code Playgroud)

如何将密钥记录/获取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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经在谷歌上搜索了,我还没有确定。

更新

目的是在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>
Run Code Online (Sandbox Code Playgroud)

Jav*_*SKT 6

你可以keyvalue像下面这样使用管道,工作示例在Stackblitz 中,你的enum语法是错误的......请检查Enums

注意:下面是Angular 6

请检查Angular 6.1 引入了一个新的 KeyValue Pipe

类型.ts 代码

export enum Type {
  USD = "US Dollar",
  MYR = "Malaysian Ringgit",
  SGD = "Singapore Dollar",
  INR = "Indian Rupee",
  JPY = "Japanese Yen"
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

更新:

对于Angular < 6,请检查 stackoverflow问题之一