How to Localize Ionic Applications with ngx-translate

Built on top of Angular, Ionic is a framework that allows creating cross-platform mobile applications. In this article, you will learn how to localize Ionic applications with ngx-translate.

In several previous articles, we explored different ways of internationalizing Angular applications: with a built-in I18n solution and by enabling in-context translations editing. In this article, we are going to make a step forward and learn how to translate Ionic applications with the help of the ngx-translate module. Ionic, as you probably know, is a framework built on top of Angular allowing to create cross-platform mobile applications. It was originally introduced in 2013 and the newest version 4 has been released recently.

The following topics are on our agenda:

  • How to create a Ionic 4 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

So, 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 Ionic 4 application compiles much slower.
  • Ionic 4, 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. Note that version 4 is currently not stable so the installer may ask whether you’d like to pick version 3 instead.

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

ionic start Translation tabs

tabs here is just a 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 require an ngx-translate module, which is a third-party solution created by Angular enthusiasts. Why don’t we use a built-in Angular module instead, you may ask. Well, unfortunately, Ionic 4 does not support this module yet, and it seems like it won’t be introduced in the near future. So, let’s stick with 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 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 working (yeah, I know, there is always some “last” and “very last step”). Open src/app/tab1/tab1.module.ts file and modify it like this:

// other imports...

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

@NgModule({
  imports: [
    // other stuff...
    TranslateModule.forChild() // add this
  ],
  declarations: [Tab1Page]
})
export class Tab1PageModule {}

In this way, we are enabling the translate pipe for the given 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 class="welcome-card">
    <ion-img src="/assets/shapes.svg"></ion-img>
    <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 {
  private language: string = this.translateService.currentLang; // 2 
}

I have pinpointed two lines of code to add:

  1. Import translation service
  2. Fetch the currently used language and store it inside the variable

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 class="welcome-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 {
  private language: string = this.translateService.currentLang;
  constructor(private translateService: TranslateService) {} // add this
 
  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 okay, though, of course, you may say "Language": "Language".

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 we 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:

//  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);
  }
}

Phrase and Translation Files

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 is 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 to easily import and export translations 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.

4.9 (98.18%) 11 votes
Comments
close

Automate Your Localization Workflow for Continuous Deployment

Automate Localization for Continuous Deployment

  • Integrate Phrase into your agile environment easily
  • Import and export your localization files in any format
  • Automate your localization workflow to speed up every release