使用角度枚举选择下拉菜单项 [英] Use enum in angular to select drop menu item

查看:38
本文介绍了使用角度枚举选择下拉菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现SELECT菜单,它根据选中的字符串使用枚举数据显示数据和保存的号码:

HTML代码:

<div class="form-group state_raw">
    <label for="state_raw">State</label>
    <select class="custom-select" name="state_raw" [(ngModel)]="merchant.state_raw" id="state_raw" required>
      <option selected></option>
      <option [value]="type" *ngFor="let type of types">{{type | formatType}}</option>
    </select>
  </div>

显示数据和转换后数值的枚举:

export enum MerchantStatusType {
  'Being set up' = 1,
  'Live for processing' = 2,
  'Trading suspended' = 3,
  'Account suspended' = 4
}

选择菜单的对象:

export class MerchantNew {
  constructor(
    public name: string,
    public address_state: string,
  ) {}
}

如何实现这一点?我要显示字符串但将数字保存到数据库?

编辑:我尝试过:

枚举:

export enum MerchantStateType {
  being_set_up = 1,
  live_for_processing = 2,
  trading_suspended = 3,
  account_suspended = 4,
}

export const MerchantStateType2LabelMapping = {
  [MerchantStateType.being_set_up]: "Being set up",
  [MerchantStateType.live_for_processing]: "Live for processing",
  [MerchantStateType.trading_suspended]: "Trading suspended",
  [MerchantStateType.account_suspended]: "Account suspended",
}

组件:

public MerchantStateType2LabelMapping = MerchantStateType2LabelMapping;

public stateTypes = Object.values(MerchantStateType);

HTML代码:

<select class="custom-select" name="state_raw" [(ngModel)]="merchant.state_raw" id="state_raw" required>
      <!--<option selected></option>-->
      <option [value]="stateType" *ngFor="let stateType of stateTypes">{{ MerchantStateType2LabelMapping[stateType] }}</option>

但是我得到了4个空行和4行状态。

推荐答案

我通常分3步完成。

首先,声明单独的枚举和从枚举值到标签的映射。这样,以后可以只在一个位置更改枚举值和标签,而无需更改任何其他代码。

// FileTypes.enum.ts

export enum FileTypesEnum {
    CSV = "CSV",
    JSON = "JSON",
    XML = "XML",
}

// optional: Record type annotation guaranties that 
// all the values from the enum are presented in the mapping
export const FileType2LabelMapping: Record<FileTypesEnum, string> = {
    [FileTypesEnum.CSV]: "Here's Csv",
    [FileTypesEnum.JSON]: "Here's Json",
    [FileTypesEnum.XML]: "Here's Xml",
};

然后将其导入组件并将其粘贴到公共属性中,以便在视图中可用:

// my.component.ts

import {FileTypesEnum, FileType2LabelMapping} from "../FileTypes.enum";

@Component({ ... })
export class MyComponent implements OnInit {
    public FileType2LabelMapping = FileType2LabelMapping;

    public fileTypes = Object.values(FileTypesEnum);

    constructor(){}
}

然后在视图中,我对枚举的值执行ngFor并将它们映射到标签:

 <!-- my.component.html -->

 <select ...>
  <option *ngFor="let fileType of fileTypes"
          [value]="fileType">
    {{FileType2LabelMapping[fileType]}}
  </option>
</select>

更新:

字符串值和数字枚举编译为不同的对象 Typescript Playground

所以看起来您必须额外过滤您的阵列

public stateTypes = Object.values(MerchantStateType).filter(value => typeof value === 'number');

这篇关于使用角度枚举选择下拉菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆