Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 430
Zaw Than oo Avatar asked Jul 23 '26 09:07

Zaw Than oo


1 Answers

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

like image 169
Sivakumar Tadisetti Avatar answered Jul 25 '26 01:07

Sivakumar Tadisetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!