typescript枚举包含值和显示名称



我一直在编写typescript,我想显示枚举字符串以外的值,但该值必须是numberic。

export enum yearofstudy {
FirstYear,
secondYear,
ThirdYear
}

在上面的代码中,我需要值为0,1,2,但显示为第一年、第二年、第三年。我该怎么做?

这就是管道在Angular中的作用。它们允许您以可重用和可缓存的方式来定义它。创建类似管道的

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

然后你可以使用

{{ yourValue | yearOfStudy }} 

我会将枚举转换为数组,然后将其绑定到select

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

在这里,我迭代枚举,然后从数组中删除数字,因为我只需要存在的值,然后我将文本和可以使用的值返回到下拉列表中。

HTML

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

这是stackblitz 的演示

最新更新