我的枚举有问题
我用字符串编写枚举,并在* ngFor
中浏览我的枚举但如果我的字符串有空格,页面会显示2个元素
这是我的枚举:
export enum ComponentCategory {
FormControls = <any> 'Form Controls',
Containers = <any> 'Containers' ,
Boxes = <any> 'Boxes',
DataPresentation = <any> 'DataPresentation',
Layout = <any> 'Layout',
Miscellaneous = <any> 'Miscellaneous',
}
例如,FormControls显示两次,如FormControls和Form Controls
谁能解决这个问题?
由于
答案 0 :(得分:1)
您不必在typescript中明确声明enum
值的字符串表示。
你可以拥有:
export enum ComponentCategory {
FormControls,
Containers,
Boxes,
DataPresentation,
Layout,
Miscellaneous
}
要将枚举成员作为字符串,您可以使用(See this SO for source):
for (var enumMember in ComponentCategory ) {
var isValueProperty = parseInt(enumMember, 10) >= 0
if (isValueProperty) {
console.log(ComponentCategory [enumMember]);
}
}
与*ngFor
...
function getEnumNames(){
var names: Array<string> = new Array<string>();
for (var enumMember in ComponentCategory ) {
var isValueProperty = parseInt(enumMember, 10) >= 0
if (isValueProperty) {
names.push(ComponentCategory [enumMember]);
}
}
return names.map(name => name.replace(/([A-Z])/g, ' $1').trim());
}
// in html
<div *ngFor="let name of getEnumNames()">