为什么 Angular 重复枚举值?

Why Angular duplicate enum values?

这是我的枚举:

export enum MyTypes {
  House = 1,
  Apartment = 2,
  Flat = 3,
  Studio = 4
}

如果我这样循环select:

<mat-select formControlName="myTypeField">
  <mat-option [value]="item.value" *ngFor="let item of myTypes"
    >{{ item.key }}
  </mat-option>
</mat-select>

显示:

1
2
3
4
House
Apartment
Flat
Studio

即显示键和值。为什么?

这是因为 TypeScript 将枚举编译成对象的方式。您可以使用 TypeScript playground 查看 how it's converted to JavaScript.

export enum MyTypes {
  House = 1,
  Apartment = 2,
  Flat = 3,
  Studio = 4
}

console.log(Object.keys(MyTypes));
// Prints: ["1", "2", "3", "4", "House", "Apartment", "Flat", "Studio"]

现场演示:https://stackblitz.com/edit/typescript-fviymz

您需要先迭代枚举并获得它自己的属性:How to get names of enum entries?