2

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?

2
  • Where you want to display? in dropdown? Commented Nov 22, 2018 at 6:14
  • @Justcode Yes. In dropdown Commented Nov 22, 2018 at 6:17

2 Answers 2

3

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 }} 
Sign up to request clarification or add additional context in comments.

2 Comments

public transform(value: YearOfStudy): string { what is YearOfStudy in this
Your enum class itself
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.