Search code examples
angularenumsrecordangular-pipe

How To Pass a Record to Angular Pipes



I'm trying to pass a record to an Angular pipe, but I cannot get rid of the parser error:

Parser Error: Unexpected token 0, expected identifier, keyword, or string at column 32 in [ {{ dto.status | mapEnumToText: { 0: 'Ok', 1: 'Error', 2: 'Review' } }} ]

<div>
    {{ dto.status | mapEnumToText: { 0: 'Ok', 1: 'Error', 2: 'Review' } }}
</div>
import { Pipe, PipeTransform } from '@angular/core';

export type enumToTextMapType = Record<number, string>;

@Pipe({
  name: 'mapEnumToText',
})
export class MapEnumToTextPipe implements PipeTransform {
  transform(value: number, enumToTextMap: enumToTextMapType): string {
    console.log(enumToTextMap);
    return enumToTextMap[value];
  }
}

My goal is to specify a mapping of enum values to texts. I know that I could also do *ngIf for each of the enum values, which is not very concise.
Specifying the map in the ts-File works, but I want to put all the texts in the html file.
myEnumMap: enumToTextMapType = { 0: 'Ok', 1: 'Error', 2: 'Review' };

The numbers 0, 1, 2 are just for testing right now and will be replaced with enum keys.


Solution

  • There is nothing wrong with your pipe. Template statements and template expressions looks like javascript, but isn't. There are many small limitations.

    Define { 0: 'Ok', 1: 'Error', 2: 'Review' } as variable in component class and use in template as argument for pipe.