【问题标题】:How can I properly bind an enum within a dropdown menu in Angular 4?如何在 Angular 4 的下拉菜单中正确绑定枚举?
【发布时间】:2019-04-22 16:45:46
【问题描述】:

在下拉菜单中,我使用了 Enum 数据结构 (Typescript) 来存储我的值。但是,与对象的类别字段的数据绑定似乎没有正确进行,默认情况下没有选择任何内容。有没有更好的解决方案?

export enum CategoryEnum {
      EXAMPLECAT1 = 1,
      EXAMPLECAT2 = 2,
      EXAMPLECAT3 = 3,
      EXAMPLECAT4 = 4
    }

@Component({
  selector: 'category',
  template: `
    <label for="appCategory">Example Category: </label>
    <select class="form-control" id="exampleCategory" required 
            (change)="parseValue($event.target.value)"
            (ngModelChange)="changeSelectedType($event)">
      <option *ngFor="let category of categoryTypes"
              [value]="category">{{category.type}}</option>
    </select>
  `
})

export class CategoryComponent {

  private selectedCategoryType: CategoryEnum
  private categoryTypes;

  constructor(){
    this.categoryTypes = CategoryMapping
  }

  parseValue(value : string) {
    this.selectedCategoryType = AppCategoryEnum[value];
  }

  //Logging: Change Selected Product type callback
  private changeSelectedType(event: any) {
    console.log(event); //object, depends on ngValue
    console.log(this.selectedCategoryType); //object, depends on ngValue
  }
}

将枚举数据类型映射到标签:

export const CategoryMapping = [
  { value: ExampleCategoryEnum.EXAMPLECAT1, type: 'Example 1' },
  { value: ExampleCategoryEnum.EXAMPLECAT2, type: 'Example 2'},
  { value: ExampleCategoryEnum.EXAMPLECAT3, type: 'Example 3'},
  { value: ExampleCategoryEnum.EXAMPLECAT4, type: 'Example 4'}
];

【问题讨论】:

  • 当您想发送非原始类型(在您的情况下为对象)时,您必须使用 [ngValue] 选项
  • 要选择一个默认值,您必须将您的ngModel(您在选择中缺少)设置为您要使用的默认值。

标签: angular typescript data-binding enums


【解决方案1】:

是的,设置

<select ... [value]="1">

其中1 是示例默认类别枚举值。

并使用category.value 代替整个对象category 作为选项值

<option ... [value]="category.value" >

并更新您的 .ts 文件以处理该更改。

【讨论】:

  • 她使用对象作为值,而不是数字
【解决方案2】:

我们可以简化与ngModel 的绑定,我创建了另一个属性来与选择元素绑定并获取属性以将值设为CategoryEnum

组件

  // I have change this to public just for demo
  public get selectedCategoryType():CategoryEnum {
    return this.selectedValue ? this.selectedValue.value: null; 
  }
  private categoryTypes;

  public selectedValue:any;

  constructor() {
    this.categoryTypes = CategoryMapping;
    this.selectedValue = this.categoryTypes[2]; // set default value 
  }

模板

<select class="form-control" id="exampleCategory" required  [(ngModel)]="selectedValue" >
      <option></option>
      <option *ngFor="let category of categoryTypes"
              [ngValue]="category">{{category.type}}</option>
    </select>
<br>

selectedCategoryType :  {{selectedCategoryType | json}}

当您想要发送非原始类型(在您的情况下为对象)时,您必须使用 [ngValue] 作为@tricheriche 所说的选项

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    相关资源
    最近更新 更多