How to use Ngx-Translate in Angular?

Vangarsushil
2 min readNov 10, 2020

--

The internationalization (i18n) library for Angular.

A simple example: https://stackblitz.com/github/vangarsushil/ngx-translate

Installation

npm install @ngx-translate/core --save

By default, there is no loader available. You can add translations manually using setTranslation but it is better to use a loader. You can write your own loader, or import an existing one. For example, you can use the TranslateHttpLoader that will load translations from files using HttpClient.

npm install @ngx-translate/http-loader --save

You have to import TranslateModule.forRoot() in the root NgModule of your application.

The forRoot static method is a convention that provides and configures services at the same time. Make sure you only call this method in the root module of your application, most of the time called AppModule.

Once you’ve decided which loader to use, you have to setup the TranslateModule to use it.

Here is how you would use them TranslateHttpLoader to load translations from "/assets/i18n/[lang].json" ([lang] is the lang that you're using, English it could be en Hindi it could be “hi” )

After creating these two files then we goto the app.component.html file

In app.component.html we pass the en.json Title pass using interpolation

<h2>{{ "HOME.TITLE" | translate }}</h2>

in the select tag, we get all list of languages.

  • In the app.componet.ts file, we used TranslateService
  • In translate.addLangs([‘en’, ‘hi’]) add a list of language codes.
  • translate.setDefaultLang(‘en’) this language will be used as a fallback when a translation isn’t found in the current language.
  • translate.use(‘hi’) the lang to use, if the lang isn’t available, it will use the current loader to get them.

Links:

Comments and thoughts are always welcome!! (: Happy Coding :)👏👏👏.

--

--

Vangarsushil
Vangarsushil

Written by Vangarsushil

The place where Angular concepts are explained

No responses yet