Software localization

How to Localize Ionic Apps with ngx-translate

Have you created a hybrid mobile app with Ionic? It's time to learn now how to localize ionic apps with the ngx-translate library.
Software localization blog category featured image | Phrase

In several previous articles, we explored different ways of internationalizing Angular applications: with its built-in I18n solution and by enabling in-context translation editing. In this article, we are going to learn how to localize Ionic apps with the help of the ngx-translate module. A framework built on top of Angular, Ionic allows for building cross-platform mobile applications and it was originally introduced in 2013. In this tutorial, we are using Ionic 5.

🗒 Note » To get the source code for the demo app, make sure you stop by at GitHub.

The following topics are on our agenda:

  • How to create a Ionic app,
  • Integrating the ngx-translate module into the app,
  • Setting a default locale and switching to another locale,
  • How to store translations and load them with an HTTP client,
  • Performing the actual translations and providing parameters to interpolate,
  • Working with translations inside the classes.

Shall we start?

Prerequisites

If you would like to follow this tutorial, install the following:

  • NodeJS version 10 or higher and NPM. Earlier versions may work as well, but the app built with Ionic 5 would compile much slower.
  • Ionic 5, which is the most recent version at the time of writing this article; to install it, run npm install -g ionic and follow the given instructions.

This is pretty much it. After you are done, create a new Ionic application by running:

ionic start Translation tabs

tabs here is just the name of the template to use.

Next, after this command is done, you should be able to cd into the Translation directory and run:

ionic serve

As a result, the server will start and your browser should open a localhost:8100 page with some boilerplate content.

Integrating ngx-translate

In order to translate our Ionic application, we will use ngx-translate, which is an open-source library created by Angular enthusiasts.

Run the following command to install ngx-translate:

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

Apart from the core library, we are also installing the http-loader, which is going to load JSON  files for us.

Now let's import all the necessary modules. Open src/app/app.module.ts file and add  the following lines:

// other imports here...

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';

import { TranslateHttpLoader } from '@ngx-translate/http-loader';

import { HttpClientModule, HttpClient } from '@angular/common/http';

Next, define an exported translations loader function:

// imports...

export function createTranslateLoader(http: HttpClient) {

  return new TranslateHttpLoader(http, './assets/i18n/', '.json');

}

This loader will fetch JSON files from the assets/i18n folder that we are going to create shortly.

Lastly, add all these modules to the imports property:

// imports and your loader...

@NgModule({

  declarations: [AppComponent],

  entryComponents: [],

  imports: [

    BrowserModule,

    IonicModule.forRoot(),

    AppRoutingModule,

    HttpClientModule, // <--- add this

    TranslateModule.forRoot({ // <--- add this

      loader: { // <--- add this

        provide: TranslateLoader, // <--- add this

        useFactory: (createTranslateLoader),  // <--- add this

        deps: [HttpClient] // <--- add this

      } // <--- add this

    }) // <--- add this

  ],

  providers: [

    StatusBar,

    SplashScreen,

    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }

  ],

  bootstrap: [AppComponent]

})

export class AppModule { }

Settings a Default  Locale

To provide a default locale, we need to modify the src/app/app.component.ts file:

// other imports...

import { TranslateService } from '@ngx-translate/core'; // add this

@Component({

  selector: 'app-root',

  templateUrl: 'app.component.html'

})

export class AppComponent {

  constructor(

    private platform: Platform,

    private splashScreen: SplashScreen,

    private statusBar: StatusBar,

    private translate: TranslateService // add this

  ) {

    this.initializeApp();

  }

  initializeApp() {

    // other stuff...

    this.translate.setDefaultLang('en'); // add this

  }

}

Here we are setting English as the default locale. If you would like to switch language, say this.translate.use('LANG_CODE'). Please note that if you do not, add this line after setDefaultLang, and the texts on the page won't be updated after language change (which is certainly an ngx-translate bug).

Performing Simple Translations

Okay, now let's translate something! Navigate to the src/app/tab1/tab1.page.html file and tweak the tab's title in the following way:

<ion-header>

  <ion-toolbar>

    <ion-title>

      {{ 'tab1.tabName' | translate }} <!-- modify this -->

    </ion-title>

  </ion-toolbar>

</ion-header>

<!-- other content goes here... -->

Here we are using the translate pipe and providing a translation key (tab1.tabName). In order to specify this translation, create two files inside the assets/i18n folder:

  • en.json
  • ru.json

Of course, you are free to choose any other locales, but I'm going to stick with English and Russian.

The dot inside the translation key means nesting, so the files should have the following contents:

en.json

{

  "tab1": {

    "tabName": "Tab One"

  }

}

ru.json

{

  "tab1": {

    "tabName": "Первая закладка"

  }

}

Nesting (or namespacing) is a very useful technique because it allows you to group related translations together. In this way, you may have namespaces like blog or admin. Also, keys under different namespaces may have the same names.

There is one last step we need to perform to make this work (yeah, I know, there is always some "last" and "very last step"). The tab pages are lazy-loaded. Therefore, we need to import the translation module into the child modules for the translations to work perfectly.

Open src/app/tab1/tab1.module.ts file and modify it like this:

// other imports...

import {  HttpClient } from '@angular/common/http';

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';

import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function createTranslateLoader(http: HttpClient) {

  return new TranslateHttpLoader(http, "./assets/i18n/", ".json");

}

@NgModule({

  imports: [

    // other stuff...

    TranslateModule.forChild({

      loader: {

        provide: TranslateLoader,

        useFactory: createTranslateLoader,

        deps: [HttpClient]

      }

    })

  ],

  declarations: [Tab1Page]

})

export class Tab1PageModule {}

In this way, we are enabling the translate pipe for the given child module.

After you have performed the above steps, reload the server. You should see that the title of the first tab now has the proper translation.

Passing Parameters to Translations

In some cases, you may need to pass parameters to your translation and interpolate it into the output string. Let me demonstrate how to do that:

<ion-header>

  <!-- header ... -->

</ion-header>

<ion-content>

  <ion-card>

    <ion-card-header>

      <ion-card-subtitle>Get Started</ion-card-subtitle>

      <ion-card-title>Welcome to Ionic</ion-card-title>

    </ion-card-header>

    <ion-card-content>

      <p translate [translateParams]="{ lang: language }">tab1.invite</p> <!-- add this -->

    </ion-card-content>

  </ion-card>

  <!-- other stuff ... -->

</ion-content>

Here we saying translate inside the p tag. Also, note the translateParams attribute which passes the actual parameters in the form of an object. lang is the parameter name, whereas language is the value. tab1.invite is our translation key.

Provide a value for this key now:

ru.json

{

  "tab1": {

    "tabName": "Первая закладка",

    "invite": "Сейчас вы выбрали {{lang}}"

  }

}

en.json

{

  "tab1": {

    "tabName": "Tab One goes here",

    "invite": "Now you have selected {{lang}}"

  }

}

The {{lang}} is interpolation — it will be replaced with the value of the language attribute passed in the template.

Now, the language variable should be defined somewhere, so let us do it inside the tab1.page.ts file:

import { Component } from '@angular/core';

import { TranslateService } from '@ngx-translate/core'; // 1

@Component({

  selector: 'app-tab1',

  templateUrl: 'tab1.page.html',

  styleUrls: ['tab1.page.scss']

})

export class Tab1Page {

  language: string = this.translateService.currentLang; // 2

  constructor(private translateService: TranslateService) {} //3

}

I have pinpointed three lines of code to add:

  1. Import translation service
  2. Fetch the currently used language and store it inside the variable
  3. Inject the translation service to the page using Dependency injection

Finally, reload the page and observe the result!

Switching Locales

Of course, the user should be able to switch the app's locale using some kind of interface. Let's code this feature now!

First of all, tweak the markup by adding a new select box:

<ion-header>

  <!--  other stuff -->

</ion-header>

<ion-content>

  <ion-card>

    <!--  other stuff -->

    <ion-card-content>

      <p translate [translateParams]="{ lang: language }">tab1.invite</p>

      <ion-item> <!-- add this block -->

        <ion-label translate>Language</ion-label>

        <ion-select [(ngModel)]='language' (ionChange)='languageChange()' [placeholder]='"tab1.languageChangePlaceholder" | translate'>

          <ion-select-option value='ru'>Russian</ion-select-option>

          <ion-select-option value='en'>English</ion-select-option>

        </ion-select>

      </ion-item> <!-- add this block (end) -->

    </ion-card-content>

  </ion-card>

  <!--  other stuff -->

</ion-content>

So, what's going on here?

  • We are adding a new item labeled as "Language" (with the translate attribute).
  • The item contains a select box that is bound to the language model.
  • Whenever a new value is selected, fire a languageChange() method.
  • The select box also has a translated placeholder.

Next, take care of the event handler by modifying the tab1.page.ts file:

//  other stuff...

export class Tab1Page {

// other code...

  languageChange() {  // add this

    this.translateService.use(this.language);  // add this

  }  // add this

}

By saying this.translateService.use(), we are actually switching the locale.

Also, let's take care of the translations for the label and placeholder:

ru.json

{

  "tab1": {

    "tabName": "Первая закладка",

    "invite": "Сейчас вы выбрали {{lang}}",

    "languageChangePlaceholder": "Выберите язык"

  },

  "Language": "Язык"

}

en.json

{

  "tab1": {

    "tabName": "Tab One goes here",

    "invite": "Now you have selected {{lang}}",

    "languageChangePlaceholder": "Change language"

  }

}

Note that I have not provided Language key at all for the English locale. Why? Well, because if the module cannot find the translation key, it will be simply printed out on the screen. For the English locale, this is totally fine, although you may also say "Language": "Language".

Execution Demo

If you reload the application, you can see the output as displayed below.

ionic-l10n-ngx-translate | Phrase

Performing Translations in Classes

Sometimes you may want to work with your translations right inside the classes. Let me show you a quick example.

First, tweak tab1.page.ts file in the following way:

//  other stuff...

export class Tab1Page {

  private language: string = this.translateService.currentLang;

  private someProperty: string = ''; // 1

  constructor(private translateService: TranslateService) {

    this.translateService.setTranslation('en', { // 2

      'tab1.getStarted': 'Get Started', // add  this

      'someProperty': 'We can use translations in {{var}}' // 3

    }); // add  this

    this.translateService.get('someProperty', { var: 'classes' }).subscribe((res: string) => { //  4

      this.someProperty = res; // 5

    }); // add  this

  }

  languageChange() {

    this.translateService.use(this.language);

  }

}

Let us move step by step:

  1. Create a new property that will be displayed in the template later on.
  2. Programmatically load new translations for the English locale. Note that by doing this we are effectively wiping out all existing translations!
  3. Providing translation with interpolation
  4. Getting translation under someProperty key (and passing a value to interpolate). We are subscribing to an event and so once the response arrives...
  5. ...we assign the received values to the someProperty attribute.

As a result, you may utilize translations inside the tab1.page.html template:

<ion-header>

  <!-- other stuff -->

</ion-header>

<ion-content>

  <ion-card class="welcome-card">

     <!-- other stuff -->

    <ion-card-content>

      <p>{{someProperty}}</p> <!-- add this -->

      <p translate [translateParams]="{ lang: language }">tab1.invite</p> <!-- add this -->

      <!-- other stuff -->

    </ion-card-content>

  </ion-card>

</ion-content>

<!-- other stuff -->

Certainly, working with translation files is not easy, especially when the app is big and supports many languages. You might easily miss some translations for a specific language, which may lead to confusion among users. It's Phrase that can make your life easier: Grab your 14-day trial.

Phrase supports many different languages and frameworks, including JavaScript, of course. It allows you to easily import and export translation data. What is cool, you can quickly understand which translation keys are missing because it is easy to lose track when working with many languages in big applications.

On top of that, you can collaborate with translators as it is much better to have a professionally done localization for your website.

Conclusion

In this article, we took a look at how to translate Ionic applications with the help of the ngx-translate module. You have learned how to provide translations and load them, how to switch locales, how to perform interpolation, and how to work with translations inside classes.

So, as you see, localizing Ionic applications is not very different from translating Angular apps – as these two technologies have many similarities. I hope that you are now ready to apply the described concepts in real projects! As always, I thank you for staying with me and until the next time.