Reputation: 33
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
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
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