0

I have an Angular 7 application that has already been built. Now we are planning to support it in to multiple languages. The issue is with success/failure messages we are showing on page depending on api calls. For this we are using one global file with variable id defined. How can I translate this file and use in the application as per locale. Currently I am importing the file, wherever used, like this.

import { GlobalMsg } from '/globalModule/globalMsg';

and using like errorMsg = GlobalMsg.errorMsg;

File globalMsg is defined like this.

export class GlobalMsg {

    // Global Msgs
    public static errorMsg = 'Some error occured';
}

Thank you.

ahmeticat
  • 1,899
  • 1
  • 13
  • 28
Taani
  • 43
  • 1
  • 10

2 Answers2

0

Instead of keeping the translated string in the GlobalMsg file, update it with translation keys.

export class GlobalMsg {
  public static errorMsg = "global.errorMsg"
}

In the translation JSON file of each locale JSON, define those keys with respective defintions

en.json

{
 global.errorMsg: "Invalid data"
}

fr.json

{
 global.errorMsg: "Données invalides"
}

HTML

<p [innerHTML]="errorMsg | translate"></p>

Component

  constructor(private translateService: TranslateService) {
    translateService.addLangs(['en', 'de']);
    translateService.setDefaultLang('en');
  }

  switchLanguage(language: string) {
    this.translateService.use(language);
  }
Ininiv
  • 1,325
  • 7
  • 12
  • How do i include the particular locale translation file. How would translate pipe understand from where to pick up translated text? – Taani Dec 03 '19 at 06:24
  • Translation module picks from the default language json file, if not changed Please refer https://angular.io/guide/i18n. – Ininiv Dec 03 '19 at 08:51
  • You need not add new translation file, update those existing translation files with the new keys and its respective translations – Ininiv Dec 03 '19 at 08:52
0

As Ininv said in his post, you're able to define translation JSON files for each locale and then translate the strings using the "translate" pipe. To manage each translation, you can use ng-translate, which is a library bundled with Angular to help with internalization.

More info here: https://github.com/ngx-translate/core

rolivencia
  • 153
  • 8