[英]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.在上面的代码中,我需要的值为 0,1,2 但显示为第 1 年、第 2 年、第 3 年。 How can I do that?
我怎样才能做到这一点?
I would convert the enum into array and then I can bind it to the select
我会将枚举转换为数组,然后我可以将它绑定到
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 HTML
<select>
<option *ngFor="let item of dropdownOfYear" [value]="item.value">{{item.text}}</option>
</select>
Here is a demo of stackblitz这是stackblitz的演示
This is pretty much what pipes are for in Angular.这几乎就是 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 }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.