Kishore Koushik
Kishore Koushik

Reputation: 33

typescript enums with value and display name

I have been working on typescript and I want display the values other than enum string but the value must be numberic.

export enum yearofstudy {
     FirstYear,
     secondYear,
     ThirdYear
}

In the above code, I need the values to be 0,1,2 but display to be 1st year, 2nd year, 3rd year. How can I do that?

Upvotes: 2

Views: 2835

Answers (2)

Ingo Bürk
Ingo Bürk

Reputation: 20043

This is pretty much what pipes are for in Angular. They allow you to define this in a reusable and cacheable way. Create a pipe like

@Pipe({name: "yearOfStudy"})
export class YearOfStudyPipe implements PipeTransform {
  public transform(value: YearOfStudy): string {
    switch (value) {
      case FirstYear: return "1st Year";
      //... 
    }
  }
}

Then you can use

{{ yourValue | yearOfStudy }} 

Upvotes: 3

Just code
Just code

Reputation: 13801

I would convert the enum into array and then I can bind it to the select

dropdownOfYear = Object.keys(yearofstudy).filter(key => !isNaN(Number(yearofstudy[key]))).map((a) => {    
  return {
    text: a,
    value: yearofstudy[a]
  }
});

Here I am iterating through the enum and then removing the numbers from the array as I only need values which are there, then I am returning the text and values which I can use into the dropdown.

HTML

 <select>
     <option *ngFor="let item of dropdownOfYear" [value]="item.value">{{item.text}}</option>
  </select>

Here is a demo of stackblitz

Upvotes: 1

Related Questions