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?
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
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 }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.