【问题标题】:Typescript Enum combined key value issueTypescript Enum 组合键值问题
【发布时间】:2019-12-03 16:05:52
【问题描述】:

我想在我的下拉列表中实现enum,但我在列表中同时获得了键和值。

我的枚举:

export enum VMRole {
    "Kubemaster" = 0, "Kubeworker" = 1, "Other" = 2
}

我正在尝试将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>

截图:

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    当您尝试使用 p =&gt; typeof p !== 'number' 过滤掉 enum 中的数字时,就会出现问题。刚刚测试了它返回的值,就像下面的数组一样 - 你可以看到数组只包含 string 值:

    所以解决方案看起来很棘手,但它可以为您完成工作:

    Object.keys(VMRole).filter(p => !Number.isInteger(parseInt(p)))
    

    甚至更简单的解决方案也适用于 TypeScript:

    Object.keys(VMRole).filter(p => isNaN(p as any))
    

    请在此处进一步阅读:

    1. Number.isInteger()
    2. parseInt()
    3. isNaN()

    希望对你有帮助!

    【讨论】:

    • 尝试过的第二种方法就像魅力一样。你得救了我的一天。谢谢!!
    猜你喜欢
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多