Here's my enum:
export enum MyTypes {
House = 1,
Apartment = 2,
Flat = 3,
Studio = 4
}
if I cycle in a select this way:
<mat-select formControlName="myTypeField">
<mat-option [value]="item.value" *ngFor="let item of myTypes"
>{{ item.key }}
</mat-option>
</mat-select>
it shows:
1
2
3
4
House
Apartment
Flat
Studio
i.e. show both keys and values. Why?
This is because of the way enums are compiled into objects by TypeScript. You can use TypeScript playground to see 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"]
Live demo: https://stackblitz.com/edit/typescript-fviymz
You'll need to first iterate the enum and get its own properties: How to get names of enum entries?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With