[英]Iterate Enum in ngFor, Angular5
I am trying to iterate an enum in TypeScript to create radio buttons corresponding to them.我正在尝试在 TypeScript 中迭代一个枚举以创建与它们对应的单选按钮。 I know how to do this using arrays but I am struggling to do it with enums.我知道如何使用数组来做到这一点,但我很难用枚举来做到这一点。
enum labelModes{
'MultiClass',
'MultiLabel'
}
@Component({
selector: 'app-label-type',
template: `
<div class="text-center p-2">
Type of labeling:<br>
<div *ngFor = "let labelMode of labelModes">
<input
type = "radio"
name = "labelType"
value = "{{labelMode}}"
(change) = "radioChangeHandler($event)"> {{labelMode}}
</div>
`
})
Nothing shows up什么都不显示
My code to iterate the enum.我的代码迭代枚举。 I had to set values for the elements and then access them using keys and objects.我必须为元素设置值,然后使用键和对象访问它们。 Ideally you should be able to do object.keys(labelModes)
instead of keys(values)
.理想情况下,您应该能够执行object.keys(labelModes)
而不是keys(values)
。 But this is the only way it worked for me.但这是它对我有用的唯一方法。
the values on the left in the enum are returned.返回枚举左侧的值。
export enum labelModes {
multiclass = "multiclass",
multilabel = "multilabel"
}
@Component({
selector: "app-label-type",
template: `
<div class="text-center p-2">
Type of labeling:<br>
<div *ngFor = "let labelMode of values">
<input
type = "radio"
name = "labelType"
value = "{{labelMode}}"
(change) = "radioChangeHandler($event)"> {{labelMode}}
</div>
`
})
export class LabelType {
ngOnInit() {}
selectedLabelType: string = " ";
values = Object.keys(labelModes);
}
You have two mistakes:你有两个错误:
Key question - do you really need an enum?关键问题 - 你真的需要枚举吗? Seems really good fit for array:似乎非常适合数组:
@Component({
selector: 'app-label-type',
template: `
<div class="text-center p-2">
Type of labeling:<br>
<div *ngFor = "let labelMode of labelModes">
<input
type = "radio"
name = "labelType"
value = "{{labelMode}}"
(change) = "radioChangeHandler($event)"> {{labelMode}}
</div>
`
})
class Component {
labelModes = ['MultiClass', 'MultiLabel']
}
Actually, enums are easy to misinterpret (especially difference between number enums and string enums), I usually prefer to replace them with plain objects or arrays if I don't use them.实际上,枚举很容易被误解(尤其是数字枚举和字符串枚举之间的区别),如果我不使用它们,我通常更喜欢用普通对象或数组替换它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.