我想在下拉列表中实现enum
,但我在列表中同时获得了键和值。
我的枚举:
export enum VMRole {
"Kubemaster" = 0, "Kubeworker" = 1, "Other" = 2
}
我的类(class)我试图将enum
分配给我的属性:
export class VirtualMachine {
role: VMRole;
...
}
我的组件:
export class AddVmComponent implements OnInit {
model: any = {};
@ViewChild('addVMForm', { static: false }) formValues;
constructor(private alertify: AlertifyService, private vm: VmService, private route:
ActivatedRoute, private http: HttpClient) {
this.model.role = Object.keys(VMRole).filter(p => typeof p !== 'number')
}
}
我的 HTML:
<select [ngModel]="model.role" class="form-control">
<option disabled>-Please choose role-</option>
<option *ngFor="let data of model.role | keyvalue">
{{data.value}}
</option>
</select>
屏幕截图:
最佳答案
当您尝试使用 p => typeof p !== 'number'
从 enum
中过滤掉数字时,就会出现此问题。刚刚测试了它返回的值,就像下面的数组一样 - 正如您所看到的,该数组仅包含 string
值:
所以这个解决方案看起来很棘手,但它适合你:
Object.keys(VMRole).filter(p => !Number.isInteger(parseInt(p)))
或者更简单的解决方案,也适用于 TypeScript:
Object.keys(VMRole).filter(p => isNaN(p as any))
请在此处进一步阅读:
希望对您有所帮助!
关于html - Typescript Enum 组合键值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59161040/