我建议您使用一个通用的管道,它将更加灵活,在您的代码中更少的冗余。
The problem with some previous propositions is that the typescript allow you to have different kind of enum, not only number/string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'enumToArray'
})
export class EnumToArrayPipe implements PipeTransform {
transform(value, args: string[]): any {
let result = [];
var keys = Object.keys(value);
var values = Object.values(value);
for (var i = 0; i < keys.length; i++) {
result.push({ key: keys[i], value: values[i] });
}
return result;
//or if you want to order the result:
//return result.sort((a, b) => a.value < b.value ? -1 : 1);
}
}
and the html will be:
<mat-select [(ngModel)]="groupKey">
<mat-option *ngFor="let group of notificationGrouping | enumToArray"
[value]="group.key">
\{\{ group.value }}
</mat-option>
</mat-select>
在其中:
public notificationGrouping : NotificationGrouping
let Number=Number;
let roles= Roles; // in .ts file
<select>
<option *ngFor="let role of roles | keyvalue" [value]="Number(\{\{role.key}})">
\{\{role.value}}
</option>
</select>
To parse a value use like below:
let selectedRoleValue= 4;
let Roles= Roles; // in .ts file
<div>\{\{Roles[selectedRoleValue]}}</div>