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

2024-06-05

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作为字符串?

有办法做吗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();
    }
}

我已经在谷歌上搜索了,但我还不太确定。

Update

目的是在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如下所示的管道,工作示例位于斯塔克闪电战 https://stackblitz.com/edit/angular-if1xbv和你的enum语法错误...请检查Enums https://www.typescriptlang.org/docs/handbook/enums.html

Note:下面一张是为了角6

请检查Angular 6.1 引入了新的 KeyValue Pipe http://www.talkingdotnet.com/angular-6-1-introduces-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;
}

组件.模板代码

<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>

Update:

For 角度 请检查 stackoverflow 之一question https://stackoverflow.com/questions/31490713/iterate-over-object-in-angular

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 TypeScript / Angular 4+ 中将 Enum 键显示为字符串 的相关文章

随机推荐