Ionic [2 & 3] | How to translate your Ionic app with ngx-translate

Written by on June 29, 2019

Ionic [2 & 3] | How to translate your Ionic app with ngx-translate

This guide will walk you through using internationalization/translate library in the Ionic Framework. We are also going to showcase several working examples to get you through.

Thankfully, there’s nothing complicated with what we are going to work with today. To achieve our goal we are going to use the ngx-translate Angular library. While there are several other approaches I chose this one as it closely resembles legacy Angular ng-translate module.

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Preparations

Please, make sure your Ionic [2|3] work environment is set up and ready. One another thing, this framework is now known simply as Ionic. Further down the line, I will refer to it only as such; I will not use version numbers, it will be referred to as Ionic.

Make sure you have these:

  • Android Environment (or iOS if you’re working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova

If you don’t have a prior Ionic installation find more information here: Ionic [2|3] | Installation Guide.

1. Update Ionic CLI

If possible you should have the latest nodeJS installation, without it, you’ll not be able to appropriately install/update Cordova and Ionic. Worst case scenario, use any recent version possible.

On the other hand, If you have already worked with Ionic/Cordova, make sure they’re up to date; older versions may not work with this tutorial:

npm install -g ionic cordova

or to do a simple update:

npm update -g ionic cordova

2. Create A New Project

ionic start IonicInternationalization blank
cd IonicInternationalization

If you prefer a working example you will find it at the end of this article; if not, keep reading.

Warning: As some of you don't have a prior Ionic CLI experience, from this point and on, every time I tell you to execute something, do that inside an example project folder.

3. Add Required Platform

Add Android platform:

ionic cordova platform add android

MacOS users can also add iOS platform:

ionic cordova platform add ios

5. Install ngx-translate library

We need these for our walk-through:

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

Example

First take a look at this embedded example:

Ionic 2 Internationalization Example

Source Walkthrough

The provided example will use two different languages: English and Croatian. Each of these languages will have a separate language JSON file.

Let us begin. Open src and assets folder. Now create the new folder and name it i18n. This name is predefined and you currently can’t configure it differently. In this newly created folder, you will need to create a new file for each required language. I will create these two files as I already told you which languages we are going to use:

src/assets/i18n/en.json
                hr.json

If you don’t know your locale name you can find it like this:

console.log(navigator.language.split('-')[0]);

This is how en.json content looks like:

{
    "PAGE_TITLE" : "Translation tutorial",	
	"BUTTONS" : {
		"btn_eng" : "English",
		"btn_cro" : "Croatian"
	},
	"IN_APP" : "Internal app translation",
	"FOO": "Foo {{test}}"
}

Next, we need to import the necessary modules in app.module.ts:

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

Don’t forget to include HttpClientModule and TranslateModule into NgModule imports:

@NgModule({
    declarations: [
        MyApp,
        HomePage
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        IonicModule.forRoot(MyApp),
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            }
        })        
    ],
    bootstrap: [IonicApp],
        entryComponents: [
        MyApp,
        HomePage
    ],
    providers: [
        StatusBar,
        SplashScreen,
        {provide: ErrorHandler, useClass: IonicErrorHandler}
    ]
})

You will also notice that TranslateModule useFactory property requires a loader factory service. This factory is called TranslateHttpLoader and it is used to load translations from “/assets/i18n/[lang].json” file. You can copy it from my example, you don’t even need to change it:

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http);
}

But, if you like a clean code you can move it into a separate Class file. Find more information here.

Now let’s initialize ngx-translate. First, in the app.component.ts, import TranslateService and include it into constructor. Finally initialize it:

import { TranslateService } from '@ngx-translate/core';
constructor(private translateService: TranslateService) {

	platform.ready().then(() => {
		translateService.setDefaultLang('en');
		translateService.use('en');            
	});
}

We have also initialized English as our default language.

At this point, the library is up and running, and both languages are available to our application.

To showcase how translation works, I have created a simple HomePage. It will have two buttons for language switching and some text where we can see these changes:

<ion-content padding>
	<h2>{{ 'IN_APP' | translate }}</h2>
	{{ 'FOO' | translate:bar }}
	<!-- Segment in content -->
	<ion-segment [(ngModel)]="relationship" color="primary" (ionChange)="segmentChanged($event)">
		<ion-segment-button value="en">
			{{ 'BUTTONS.btn_eng' | translate }}
		</ion-segment-button>
		<ion-segment-button value="hr">
			{{ 'BUTTONS.btn_cro' | translate }}
		</ion-segment-button>
	</ion-segment>
</ion-content>

As you can see, the used syntax is equal to old ng/ng2-translate implementation.

For those of you who never worked with previous translate implementations, this line:

{{ 'BUTTONS.btn_eng' | translate }}

will pull BUTTONS.btn_eng content from the currently active JSON file. Let’s say en is our currently configured language. BUTTONS.btn_eng will translate to this line:

"BUTTONS" : {
	"btn_eng" : "English"
}

But what if we want to provide translations directly in our JavaScript code? You can use this syntax:

translateService.setTranslation('en', {
	IN_APP : 'Internal app translation'
});

translateService.setTranslation('hr', {
	IN_APP : 'Prijevod unutar aplikacije'
});

You can also test it in the provided example, just uncomment above shown lines.

Source Code

In case GitHub repo is not available, and you can only use code provided below, this is what project folder looks like (image was taken from the Sublime text editor):

Ionic 2 Internationalization Folder Structure

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http);
}

@NgModule({
    declarations: [
        MyApp,
        HomePage
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        IonicModule.forRoot(MyApp),
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            }
        })        
    ],
    bootstrap: [IonicApp],
        entryComponents: [
        MyApp,
        HomePage
    ],
    providers: [
        StatusBar,
        SplashScreen,
        {provide: ErrorHandler, useClass: IonicErrorHandler}
    ]
})
export class AppModule {}
app.component.ts
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

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

import { HomePage } from '../pages/home/home';

@Component({
    templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

    constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private translateService: TranslateService) {

        platform.ready().then(() => {
            statusBar.styleDefault();
            splashScreen.hide();

            translateService.setDefaultLang('en');
            translateService.use('en');            
        });
    }
}
home.html
<ion-header>
	<ion-navbar>
		<ion-title>{{ 'PAGE_TITLE' | translate }}</ion-title>
	</ion-navbar>
</ion-header>

<ion-content padding>
	<h2>{{ 'IN_APP' | translate }}</h2>
	{{ 'FOO' | translate:bar }}
	<!-- Segment in content -->
	<ion-segment [(ngModel)]="relationship" color="primary" (ionChange)="segmentChanged($event)">
		<ion-segment-button value="en">
			{{ 'BUTTONS.btn_eng' | translate }}
		</ion-segment-button>
		<ion-segment-button value="hr">
			{{ 'BUTTONS.btn_cro' | translate }}
		</ion-segment-button>
	</ion-segment>
</ion-content>
home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

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

@Component({
	selector: 'page-home',
	templateUrl: 'home.html'
})

export class HomePage {

	bar = { "test": 'bar' };

	constructor(public navCtrl: NavController, private translateService: TranslateService) {

        /*translateService.setTranslation('en', {
            IN_APP : 'Internal app translation'
        });

        translateService.setTranslation('hr', {
            IN_APP : 'Prijevod unutar aplikacije'
        });*/
	}

	segmentChanged(event) {
		this.translateService.use(event._value);
	}
}
en.json
{
    "PAGE_TITLE" : "Translation tutorial",	
	"BUTTONS" : {
		"btn_eng" : "English",
		"btn_cro" : "Croatian"
	},
	"IN_APP" : "Internal app translation",
	"FOO": "Foo {{test}}"
}
hr.json
{
    "PAGE_TITLE" : "Uputstva za prijevod",	
	"BUTTONS" : {
		"btn_eng" : "Engleski",
		"btn_cro" : "Hrvatski"
	},
	"IN_APP" : "Prijevod unutar aplikacije",
	"FOO": "Bu {{test}}"
}

Deployment

Next step, build our application:

ionic build android

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

Finally:

ionic run android -l -c -s

or if you want to test it in your browser:

ionic serve -l -c -s

Download The Code

Working GitHub repo link can be found below:

GitHub
Categories

Leave a Reply