Angular 管道从枚举值中提取,但对任何枚举都是通用的

Angular Pipe extracts from Enum values, but generic for any Enum

我有一个枚举,其中包含分配给元素的字符串。不幸的是,它不适用于整数作为索引。 RoleTypesEnum[0] => 未定义。我做了一个 Pipe 解决了这个问题。

export enum RoleTypesEnum {
    RoleA = 'Role is A',
    RoleB = 'Role is B',
}

//HTML ('opt' integer received from backend)
{{ RoleTypesEnum[opt] | enumIntToDescription}}
@Pipe({
    name: 'enumIntToDescription',
})
export class EnumIntToDescriptionPipe implements PipeTransform {
    transform(value: number): string {
        return Object.values(RoleTypesEnum )[value];
    }
}

但我想让它通用以适用于任何枚举类型,而不仅仅是 RoleTypesEnum。 是否有适用于任何枚举的解决方案?也许使用泛型 EnumIntToDescriptionPipe?

如果你想让它成为通用的,你可以将枚举的值传递给管道。

{{ opt | enumIntToDescription: RoleTypesEnum }} 
@Pipe({
    name: 'enumIntToDescription',
})
export class EnumIntToDescriptionPipe implements PipeTransform {
    // enum object on which you want this pipe to work
    transform(value: number, enum: any): any {
        return Object.values(enum)[value];
    }
}

在您的组件中,您可以将枚举值传递给管道,它会按预期工作。