我正在使用Angular2和Typscript。我有一个枚举:
export enum Role {
ServiceAdmin, CompanyAdmin, Foreman, AgentForeman,
CrewMember, AgentCrewMember, Customer
}
我想使用* ngFor遍历枚举。做这个的最好方式是什么?我必须创建一个管道吗?还是有更简单的方法?
Answers:
枚举只是一个对象。
您的枚举是用JavaScript编写的,如下所示:
{
0: "ServiceAdmin",
1: "CompanyAdmin",
2: "Foreman",
3: "AgentForeman",
4: "CrewMember",
5: "AgentCrewMember",
6: "Customer",
ServiceAdmin: 0,
CompanyAdmin: 1,
Foreman: 2,
AgentForeman: 3,
CrewMember: 4,
AgentCrewMember: 5,
Customer: 6
}
因此,您可以通过以下方式进行迭代(plnkr):
@Component({
...
template: `
<div *ngFor="let item of keys()">
{{ item }}
</div>
`
})
export class YourComponent {
role = Role;
keys() : Array<string> {
var keys = Object.keys(this.role);
return keys.slice(keys.length / 2);
}
}
或者创建自定义管道会更好:
@Pipe({
name: 'enumToArray'
})
export class EnumToArrayPipe implements PipeTransform {
transform(data: Object) {
const keys = Object.keys(data);
return keys.slice(keys.length / 2);
}
}
更新资料
Typescript 2.4允许枚举成员包含字符串初始化器,例如:
enum Colors {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
在这种情况下,您可以Object.keys(data);
从管道返回。
return Object.keys(data);
role = Object.keys(Role)
在组件中使用即可。
您可以只使用Angular 6.1中引入的“键值”管道。
<p *ngFor="let enum of TestEnum | keyvalue">
{{ enum.key }} - {{ enum.value}}
</p>
模板的范围是组件实例。如果要访问此范围之外的内容,则需要通过使用组件实例使其可用:
如果枚举键不以0开头,这也适用
@Pipe({name: 'enumToArray'})
export class EnumToArrayPipe implements PipeTransform {
transform(value) : Object {
return Object.keys(value).filter(e => !isNaN(+e)).map(o => { return {index: +o, name: value[o]}});
}
}
@Component({
...
imports: [EnumsToArrayPipe],
template: `<div *ngFor="let item of roles | enumToArray">{{item.index}}: {{item.name}}</div>`
})
class MyComponent {
roles = Role;
}
我需要做同样的事情,也许这就是您想要的。
更干燥,也可以使用module
。
export enum Role {
ServiceAdmin, CompanyAdmin, Foreman, AgentForeman,
CrewMember, AgentCrewMember, Customer
}
export namespace Role {
export function keys(): Array<string>{
var keys = Object.keys(Role);
return keys.slice(keys.length / 2, keys.length-1);
}
}
切片之前的对象输出
{
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"ServiceAdmin",
"CompanyAdmin",
"Foreman",
"AgentForeman",
"CrewMember",
"AgentCrewMember",
"Customer",
"keys"
}
打字稿合并两个声明,因此 keys.lenght-1
和ngFor
:
<div *ngFor="let role of Roles.keys()">{{ role }}</div>
更多信息:
Typescript的声明合并
基于:
TypeScript:向枚举添加函数
https://basarat.gitbooks.io/typescript/content/docs/enums.html(在枚举章的最后)。
keys.lenght-1
export enum Priority {
LL = 1, // VERY LOW
L = 2, // LOW
N = 3, // NORMAL
U = 4, // HIGH
UU = 5 // VERY HIGH
}
您的角度component.ts:
import { Priority } from './../shared/core/config/datas.config';
@Component({
selector: 'app-yourcomponent',
template: `
<ng-container *ngFor="let p of getPriority">
<div> {{p.key}} / {{p.value}} </div>
</ng-container>
`
})
export class YourComponent {
getPriority = this.getENUM(Priority);
getENUM(ENUM:any): string[] {
let myEnum = [];
let objectEnum = Object.keys(ENUM);
const values = objectEnum.slice( 0 , objectEnum.length / 2 );
const keys = objectEnum.slice( objectEnum.length / 2 );
for (let i = 0 ; i < objectEnum.length/2 ; i++ ) {
myEnum.push( { key: keys[i], value: values[i] } );
}
return myEnum;
}
}
我有枚举:
export enum FileCategory {
passport = 'Multipass',
agreement = 'Personal agreement',
contract = 'Contract',
photo = 'Self photos',
other = 'Other'
}
在ts文件中:
export class MyBestComponent implements OnInit {
fileCategory = FileCategory;
// returns keys of enum
fileKeys(): Array<string> {
const keys = Object.keys(this.fileCategory);
return keys;
}
// returns values of enum
fileVals(): Array<string> {
const keys = Object.keys(this.fileCategory);
return keys.map(el => Object(this.fileCategory)[el]);
}
在HTML模板中显示以下枚举的值和键:
<a *ngFor="let cat of fileVals()"
(click)="addFileCategory(cat)">{{cat}}</a>
<a *ngFor="let cat of fileKeys()"
(click)="addFileCategory(cat)">{{cat}}</a>
使用管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'enum'
})
export class EnumSelectPipe implements PipeTransform {
transform(value: any): [number, string][] {
return Object.keys(value).filter(t => isNaN(+t)).map(t => [value[t], t]);
}
}
并在模板中:
<mat-select formControlName="type" placeholder="Package Type">
<mat-option *ngFor="let pType of PackageTypes | enum" [value]="pType[0]">{{ pType[1] | title}}</mat-option>
</mat-select>
我建议您使用通用Pipe,它将在您的代码中更加灵活和减少冗余。先前的命题的问题在于,打字稿允许您使用不同种类的枚举,而不仅仅是数字/字符串。
例如:
export enum NotificationGrouping {
GroupByCreatedAt = "GroupByCreatedAt",
GroupByCreatedByUser = "GroupByCreatedByUser",
GroupByEntity = "GroupByEntity",
GroupByAction = "GroupByAction",
}
这是我的解决方案:
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);
}
}
和html将是:
<mat-select [(ngModel)]="groupKey">
<mat-option *ngFor="let group of notificationGrouping | enumToArray"
[value]="group.key">
{{ group.value }}
</mat-option>
</mat-select>
在ts中:
public notificationGrouping : NotificationGrouping
注意:看到人们在不加解释的情况下放减号还是很有趣的。对于其他对此解决方案可能感兴趣的人,我可以确认它是否正确运行。
ES6支持
export enum E {
a = 'First',
b = 'Second',
c = 'Third'
}
let keyValueArray = Object.keys(E).map(k => ({key: k, value: E[k as any]}));
在Angular 7中,使用keys()时仍会获得所有键和值的列表。
基于以上答案,我将其用于一个简单的ENUM,看起来更干净,更OO:
export enum CategoryType {
Type1,
Type2,
...,
}
export namespace CategoryType {
export function keys() {
return Object.keys(CategoryType).filter(k => !isNaN(Number(k)));
}
}
然后在模板中:
<option *ngFor="let type of types.keys()" [value]="type">{{types[type]}}</option>
该函数成为枚举中的另一个条目,但像其他非数字一样被过滤掉。