Translate Enum Keys with i18n in Angular and bind to MatSelection

Viewed 26

I have an Enum like this

export enum LogEvent
{
    All = 0,
    Created = 1,
    Modified = 2,
    Delete = 3
}

I want to convert these enum keys with i18n translation and bind them to MatSelection. The selected value should be the number.

Please help me with this.

1 Answers

You can try:

  1. Create Pipe transfrom like this with i18n:

     @Pipe({
         name: 'textLogEvent',
         pure: false 
     }) 
     export class LogEventPipe implements PipeTransform {
         constructor(private translate: TranslateService) { }
    
     transform(value: Enums.LogEvent) {
         try {
             switch (+value) {
                 case Enums.LogEvent.All:
                     return this.translate.instant('t-all');
                 case Enums.LogEvent.Created:
                     return this.translate.instant('t-created');
                 case Enums.LogEvent.Modified:
                     return this.translate.instant('t-modified');
                 case Enums.LogEvent.Delete:
                     return this.translate.instant('t-delete');
                 default:
                     return this.translate.instant('t-undefined');
             }
         } catch (ex) {
             return '';
         }
      } 
    }
    
  2. In the mat selection you can use pipe text to load this enum value number like:

    {{ value | textLogEvent }}
    

Hope this help!

Related