Issue
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>
Solution
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
Answered By - Sivakumar Tadisetti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.