Angular Translate

Angular translate module

Dynamic labels can be generated, translated with the user’s language and/or language administration.

All starts with the import of translation modules:

npm i @ngx-translate/core --save
npm i @ngx-translate/http-loader --save

Then generate our json with the translations of the labels:

// /assets/locale/it.json
{
  "HOME": {
    "WELCOME_TEXT": "Hello "
  },}

In our module we will add imports and a function to load an external file.

// /app/app.module.ts
...
imports: [
  TranslateModule.forRoot({ // Import the Translate module and the loader
    loader: {
      provide: TranslateLoader,
      useFactory: HttpLoaderFactory,
      deps: [HttpClient]
    }
  }),
]
...

/**
* Can also use a custom loader like a global javascript variable or use Google translate
* @param {HttpClient} http
* @returns {TranslateHttpLoader}
* @constructor
*/
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, '/assets/locale/', '.json');
}

In a component we have to start our translating service.

// /app/app.component.ts
import { TranslateService } from '@ngx-translate/core';
...

  constructor(private _router: Router,
              private _translate: TranslateService) {
    this.setDefaultLanguage();
  }

  private setDefaultLanguage() {
    let userLang = UsersService.getLang() || navigator.language;
    if (userLang.length > 2) {
      userLang = userLang.split('-')[0];
    }
    let currentLang = Constants.DEFAULT_LANG;
    if (Constants.PORTALS_LANGUAGES.indexOf(userLang) > -1) {
      currentLang = userLang;
    }
    this._translate.setDefaultLang(currentLang);
  }

The core is the following call to the translation service, to set our default language:

this._translate.setDefaultLang(currentLang);

We can also change the user’s language, perhaps by clicking on a flag button on the component:

// /app/app.component.ts
...
  switchLanguage(language: string) {
    console.log('Switch language:', language);
    this._translate.use(language);
  }
...

If we are inside the template, it boils down to a translation pipe.

{{ 'my.translation.key' | translate }}

If, on the other hand, we are inside the component, the matter becomes slightly more complicated.
We have three possible recipes to draw from:

  • translate.instant('ID'): f you are sure that your translation files are already loaded and you don’t want to update the translations automatically if a language changes.
  • translate.get('ID'): if you are not sure about the loading state but you don’t need updates on language changes. It gives you an observable that returns the translation once it’s loaded and terminates the observable.
  • translate.stream('ID'): if you want constant updates (e.g. when a language changes). It returns an observable that emits translation updates. Make sure to dispose the observable if you don’t need it anymore.

Below is an example from inside a component:

constructor(translate: TranslateService) {
  translate.get('my.translation.key').subscribe((text:string) => {console.log(text});
}


Try it at home!

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.