Zaw Than oo
Zaw Than oo

Reputation: 9935

Display Enum key as string in TypeScript / Angular 4+

export enum Type {
    TYPE_1 : "Apple",
    TYPE_2 : "Orange",
    TYPE_3 : "Banana"
}

When I log Type.TYPE_1, toString method is called by default.

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

Output => Apple is Apple

My expectation is result is like

Output : TYPE_1 is Apple

How can I log/get the key TYPE_1 as string?

Is there way to do override method like as below?

export enum Type {
    TYPE_1 : "Apple",
    TYPE_2 : "Orange",
    TYPE_3 : "Banana"

    toString() {
        this.key + " is " + this.toString();
        <or>
        this.key + " is " + this.value();
    }
}

I already googling for that, I am not OK yet.

Update

The purpose is to show in 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>

Upvotes: 7

Views: 28039

Answers (4)

Dirk Wessels
Dirk Wessels

Reputation: 369

I just have a function in my .ts file

StoreListingTypeString(type: StoreListingType): string {
  return StoreListingType[type];
}

Then call that function in my html

{{StoreListingTypeString(listing.listingType)}}

Upvotes: 3

Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5041

You can use keyvalue pipe like below, working example is here in Stackblitz and your enum syntax is wrong... please check Enums

Note: Below one is for Angular 6

Please check Angular 6.1 introduces a new KeyValue Pipe

types.ts code

export enum Type {
  USD = "US Dollar",
  MYR = "Malaysian Ringgit",
  SGD = "Singapore Dollar",
  INR = "Indian Rupee",
  JPY = "Japanese Yen"
}

Component.ts code

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 code

<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 Angular < 6 please check one of the stackoverflow question

Upvotes: 8

Arnab_Ghosh
Arnab_Ghosh

Reputation: 319

Few clarifications before we get to the answer,

  • As others already mentioned, the string enum syntax should be -
export enum Currency {
  USD = "US Dollar",
  MYR = "Malaysian Ringgit",
  SGD = "Singapore Dollar",
  INR = "Indian Rupee",
  JPY = "Japanese Yen"
}
  • I don't think here the toString method understanding is right. Consider it more like an JS object: const currency = { "USD" : "US Dollar", "MYR" : "Malaysian Ringgit" } When you're passing a key to a object, its always gonna return the value, irrespective of whether you use toString or not.

Now coming to the solution , I have never worked in Angular, so advance apologies for Angular syntax. But I faced a similar issue where I needed to show the key strings in a dropdown.I made it work by looping through the enum as an object. For this specific problem, instead of,

const currencyList : Currency[]= [Currency.USD, Currency.MYR, Currency.SGD, Currency.INR, Currency.JPY];

I might have done :

const currencyCodes = Object.keys(Currency) 
<table>
    <tr *ngFor="let currencyCode of currencyCodes">
        <td>
            <input name="radioGroup" type="radio" [(ngModel)]="selectedType" [value]="currency">
            <label>{{currencyCode}} is {{Currency[currencyCode]}}</label>
        </td>
    </tr>
</table>

Upvotes: 0

Noor A Shuvo
Noor A Shuvo

Reputation: 2807

Firstly, enum syntax will be

enum Type {
    TYPE_1 = "Apple",
    TYPE_2 = "Orange",
    TYPE_3 = "Banana"
}

By default, you can not do this straightforwardly. You can't get the keys of your enum. But, you can achieve it by iteration, which will not be the best thing you know. You can try

console.log(Object.keys(Type).find(key => Type[key] === Type.TYPE_1)+ " is "+ Type.TYPE_1);

Update:

As you construct the array manually

currencyList : Currency[]= [Currency.USD, Currency.MYR, Currency.SGD, Currency.INR, Currency.JPY]; 

then, why not add a map here and then iterate through it

let curList = new Map()
    .set("USD","US Dollar")
    .set("MYR","Malaysian Dollar")
    .set("SGD", "Singapore Dollar");

etc..

Upvotes: 1

Related Questions