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, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here, again leave me a comment below. I'm here to help you, I expect the same from you. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com, or follow and mention me on twitter (@gajotres). Thanks and have a nice day!

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
Is Ionic (2 or 3) causing you problems? Are you struggling with your application? Trust me, I was in the same situation like you. If you require more information beyond the subject of this article, you will probably find it in a list below. Take a look; if there’s a topic not covered here, leave me a comment, and I will do my best to cover it.
 
 

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 walkthrough:
 
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader
 

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.
 
Continue to the next page

  • Patrice Havre

    Is there some changes with the alpha 51 ? While it works in my browser and ionic view (perfectly) but when built for android everything translation is blank. Does it do not find the directory ? In fact if I use the setTranslation instead of the useStatisFileLoader function it works also on android … Am I missing some file access rights settings in android ?

    • I’m sorry this was my mistake. I forgot to add a chapter dedicated to Cordova Whitelist plugin which is required for Android or iOS deployment.

      Look at a chapter: 4. INSTALL CORDOVA WHITELIST PLUGIN

      Unfortunately, you will need to download GitHub code again. First add Cordova Whitelist plugin then add required platform.

      • Patrice Havre

        Is the install order important ? For I already have my android platform installed and now the the plugin has been installed and the index.html set as you specified, some http.get which wasn’t working until now on my android devices now are ok (So I guessed the install is correct) BUT for my translation files it still is not working … 🙁
        I added some tag in the config.xml but with no improvement whatsoever.

        • Some Cordova plugins required specific platform to be installed in advanced. What specific part of code is causing you problems?

          • Patrice Havre

            Well I don’t know for it seems that I followed every chapter as specified but it still is not working in my android device (no translation, everything is blank whereas I’m sure the plugin is working since my http get calls are now allowed). The only difference is that I could not execute the add android platform since it is already existing.

          • I just tried it again and it’s working on my Android smartphone. But let’s do it from a different perspective.

            Follow these instructions:

            1. git clone https://github.com/Gajotres/Ionic2InternationalizationExample.git
            2. cd Ionic2InternationalizationExample
            3. ionic platform add android
            4. cordova plugin add cordova-plugin-whitelist
            5. npm install
            6. ionic serve -> To see if everything is working just fine
            7. ionic run android -l -c -s

          • Marcus Asplund

            Hi, good article and example, but unfortunately i am getting the same error as Patrice.
            I followed the steps, everything is fine in browser with $ ionic serve, but $ ionic build android and then install .apk on my physical device (Nexus 4 with Android 5.1.1)

            $ ionic info
            Cordova CLI: 6.0.0-dev (cordova-lib@5.4.1)
            Gulp version: CLI version 3.9.0
            Gulp local:
            Ionic Version: 2.0.0-alpha.51
            Ionic CLI Version: 2.0.0-beta.17
            Ionic App Lib Version: 2.0.0-beta.8
            OS: Distributor ID: Ubuntu Description: Ubuntu 14.04.3 LTS
            Node Version: v5.4.1

            I am getting same error i a larger app i am building as well; everything works fine on browser, but nothing is diplayed in a .apk on a physical device.
            I am running Linux on a Chromebook, so i have (at least not for the moment, it is quirky) any possibility to run an android emulator.

          • Could you please downgrade cordova to 5.X version. Cordova 6 don’t work properly with Ionic1 or Ionic2.

          • Marcus Asplund

            Downgraded and done all steps again from fresh, with the same result. 🙁
            Cordova CLI: 5.4.1

          • Have you tried Chrome Remote Debugging to see what’s happening?

          • Marcus Asplund

            I’ll try to set up some proper debugging tonight, will come back when find out what is going on here.

          • I would appreciate that.

          • Marcus Asplund

            Got it working in my large app now, after debugging i found out that there was an extra slash added in the path to the json, producing a 404, so no translations available then.
            Before:
            var prefix = ‘assets/i18n/’;
            var suffix = ‘.json’;
            path: file:///android_asset/www/assets/i18n//sv.json = 404

            Now:
            var prefix = ‘./assets/i18n’;
            var suffix = ‘.json’;
            path: file:///android_asset/www/assets/i18n/sv.json = 200 OK

            I will try to step through your tutorial once more step-by-step and see if the same error occurs

          • That’s good to know, I’ll add this as a warning for other people to careful.

          • rut

            How can I implement localization for plugin-command-buttons, like “ok” or “cancel” at ion-select element?

          • anonymous
  • Great tutorial! 🙂 Is there some kind of “generator”, which would pick all strings and create a json file for you? So, you could just translate them then?

    • Sorry I don’t understand the context. From where it will pull all strings?

      • I am sorry. What I meant was to pick all the strings from html file {{ string | translate }} and automatically build en.json file. You could then copy file and translate it. All clear now? 🙂

  • Amyou Teddy

    Before I use in javascript side like this
    $translate.instant(‘hello’);
    But in ionic2 i can’t use anymore.

  • Paolo Torrico

    what if i have 10 pages and i have to use translation each of 10 pages? In my main class App I inject TranslateService, then for each page i have to inject the TranslateService? What if i have to translate the same word in different pages, can i reuse the same code?

    Thank you for your article, it is great!

  • Omar Hassan

    How i can read localized values from javascript/typescript side ?

  • Phone Gapps

    I’m quite new to Ionic. Is that normal to put the “assets” folder inside of “www” instead of inside of the “app” folder?

  • Cristian

    How can you translate text that is in the .ts file. For example an ActionSheet text.

  • Matt

    Is there a way to pass in dynamic values? Similar to PHP sprintf where you could have something like “You have %d messages” and it translates with the number of messages in the message.

  • Roman Kevin Lumanlan

    i think this is already outdated. ca you post an updated tutorial of ionic 2 internationalize-and-localize-your-app in javascript

    • Throze

      Are you getting an error with UseStaticFilesLoader too?

      • Roman Kevin Lumanlan

        i am having this error EXCEPTION: No Pipe decorator found on TranslatePipe

        • Can Kattwinkel

          see the link i mentioned above.

          • Roman Kevin Lumanlan

            what link?

    • The tutorial has been updated to the current Ionic version.

  • Amr Khudair

    good tutorial

  • Szymon Stasik

    Thanks for nice post! How to avoid delaying first render and ensure at the same time that first renders will happen only after translations are ready?

    • Currently the only thing you can do is to delay application load. The same thing worked in Ionic 1. It’s simply an downside of async loading. Here’s a working example: https://github.com/ngx-translate/core/issues/517 just search for a kneefer comment (it should be third from the end).

  • Felipe Moura

    Thanks for the tutorial! But when the application closes and reopens the default language reappears. How to always keep the new language chosen?

    • Store your selected language into local-storage and load it again during next app initialization.