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?
If you want to make it generic, you can pass the value of enum to the pipe.
{{ 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];
}
}
In your component, you can pass the enum value to the pipe and it will work as expected.