angulartypescriptngx-translate

How to translate enums at angular 6


I am trying to translate the enums at the Angular but the problem it is that I don't know how to translate them. I can read them, I can show in a dropdown but not to translate.

Below is my code

export enum test {
 test1 = '1 - do something',
 test2 = '2 - do anything',
}

I read the data something like this

public getEnum: any = {};

public ngOnInit(): void {
Object.values(test).map(a: string) => {

const id = a.substr(0, 5);
this.getEnum[id] = a;
}

And in the html I have something like this

 [options]="getEnum"

The translate is something like this.

"dropdown": {
  "doSomething": {
    "test1": "1 - do something"
   }
}

Solution

  • I suggest little bit different approach. Do not translate it: keep in enum keys to translation.json file e.g.

    export enum Test {
     test1 = 'dropdown.doSomething.test1',
     test2 = 'dropdown.doSomething.test2',
    }
    

    I that case enum will not depend on current language and you will be able to easily translate value from enum by:

    const enTranslations = {
      dropdown: {
        doSomething: {
         test1: "1 - do something"
        }
      }
    };
    
    const getTranslatedText = (tranlations, keys: string[]) => keys.reduce((acc, curr) => acc[curr], translations);
    
    const key1 = Test.test1
    const translatedEnText = getTranslatedText(enTranslations, key1.split('.'));
    

    Then you can display translatedEnText, or pass it into function call. translatedEnText === '1 - do something'

    If you want to have text from the same key in different language just call getTranslatedText with other translation object e.g. deTranslations

    If you want to map your enum into object with same keys and translated values do something like this:

    const testEng = Object.values(Test).reduce((acc, key) => ({ ...acc, [key]: getTranslatedText(enTranslations, key.split('.'))}), {})
    

    reducde will start with {} in acc and on each iteration step it will add to acc translated text from getTranslatedText(enTranslations, key.split('.')) (as value) under key key.

    Playground