枚举值的角管提取物,但对于任何枚举
我有一个枚举,其中包含分配给元素的字符串。不幸的是,它不能使用整数作为索引。 RoleTypesEnum[0] =>不明确的。我制作了一个管道来解决这个问题。
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];
}
}
但我想让它通用以适用于任何 Enum 类型,而不仅仅是 RoleTypesEnum。 是否有适用于任何枚举的解决方案?也许使用泛型 EnumIntToDescriptionPipe?
I have an enum with strings assigned to elements. Unfortunately, it does not work with integers as indexes. RoleTypesEnum[0] => undefined. I made a Pipe which solves this problem.
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];
}
}
But I want to make it generic to work for any Enum type, not only RoleTypesEnum.
Can there be a solution to work for any enum? Maybe with generics EnumIntToDescriptionPipe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你想让它通用,你可以将 enum 的值传递给管道。
在您的组件中,您可以将枚举值传递给管道,它将按预期工作。
If you want to make it generic, you can pass the value of enum to the pipe.
In your component, you can pass the enum value to the pipe and it will work as expected.
我已经尝试了上面的解决方案,但是对我有用的方法是在做更具体的情况:
我的EnumToDeScriptionPipe文件:
我的HTML:
正如我所说的那样,这是我更喜欢的更具体而不是通用的解决方案。
重要!对于使用 Angular 的人:
如果您仍然无法使用管道或正在收到错误请记住在 app.module 和 component_name.module 中声明
它 applicationPipeSmodule 用于声明的管道,并在 app.module 和 component_name.module 中声明为:
I've tried the solutions above but what worked for me was doing something more specific to the case:
My EnumToDescriptionPipe file:
My HTML:
As I said this is a more specific, not generic, solution which I preferred.
Important! For those using Angular:
If you still cant apply the pipe or is receiving an error remember to declare it in app.module and in component_name.module
I particularly created an ApplicationPipesModule for my pipes declaration and declared it in app.module and in the component_name.module: