In my previous Ionic 2 based article: Having Fun With Cordova Geolocation Plugin, I showed you how to integrate Cordova Geolocation plugin into your Ionic 2 application. Now let’s try something completely different, I’ll show you how to implement internationalization and localization using ng2-translate plugin.
 
 

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

 
Ionic 2 is causing you problems? Are you struggling to make it work? Trust me, I wasn’t in any better situation. 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 there, leave me a comment and I’ll cover it.
 
 

Preparations

 
Before we can begin, make sure you have everything preconfigured for Ionic 2.
 
You should have these:
 
  • Android Environment (or iOS if you’re working on a MacOS)
  • nodeJS
  • Ionic 2
  • Cordova
 
Find more information here: Ionic 2 | Installation Guide if you don’t have a previous Ionic 2 installation or if you have never read my previous articles on this topic.
 

1. Update Ionic & Cordova

 
You need to have a latest nodeJS version, without it, you’ll not be able to install/update Cordova and Ionic appropriately.
 
If you have a previous Ionic/Cordova installation make sure its up to date, older versions may not work with this tutorial. Though latest versions may also mess things up:
 
npm install -g ionic@beta
 
or you can even do it like this:
 
npm update -g ionic@beta
 
I will remove beta keyword once Ionic 2 reach RC status.
 
Warning: Ionic2 is still in alpha status so the final implementation may differ from this code. I will update this article if and when that happens.
 
 
 

2. Create A New Project

 
ionic start Ionic2InternationalizationExample blank --v2
cd Ionic2InternationalizationExample
 
Open app directory and remove all content from a directory called pages but don’t delete it. Somewhere below you’ll find a link to GitHub repo holding a working example (or you can copy past provided code). Download zipped project repo folder, copy app and www directory and past it into a newly created folder.
 
Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.
 

3. Add Required Platform

 
Add Android platform:
 
ionic platform add android
 
MacOS users can also add iOS platform:
 
ionic platform add ios
 

4. Install Cordova Whitelist plugin

 
If you’re using Cordova 4+ and especially if you’re accessing remote content don’t forget to install Cordova Whitelist plugin:
 
cordova plugin add cordova-plugin-whitelist
 
Open www folder and add this security meta tag to index.html file:
 
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
 

5. Install ng2-translate

 
Don’t forget to do this from the project folder:
 
npm install ng2-translate --save
 

Example

 
First take a look at this embedded example:
 
Ionic 2 Internationalization Example
 

Source Walkthrough

 
This example will use three different languages: English, German, and Croatian. Each language will have a specific internationalization file, and each one of them will hold a json content.
 
Open www foder and create assets folder, now open newly created assets folder and create another one called i18n.
 
Create as many json files whose names are equal to a specific locale/language name. For example, we will work with en, de and hr locals, so our file structure should look like this:
 
wwww/assets/i18n/en.json
                 de.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 what en.json content looks like:
 
{
	"title" : "Internationalization Example",	
	"segment": {	
  		"puppies": "Puppies",
  		"kittens": "Kittens"
	}
}
 
Let’s get back to our code; open app.js and import ng2-translate:
 
import {TranslateService, TranslatePipe} from 'ng2-translate/ng2-translate';
 
Add these services into @App decorator like this:
 
@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers: [TranslateService],
  pipes: [TranslatePipe]
})
 
Inject them into every class constructor that requires internationalization:
 
  constructor(platform: Platform, translate: TranslateService,) {
    this.rootPage = HomePage;
    this.translate = translate;    
 
For the last step of app initialization, we need to configure ng2-translate service. We will use a function called initializeTranslateServiceConfig:
this.initializeTranslateServiceConfig(); 
 
Function content looks like this:
 
  initializeTranslateServiceConfig() {
    var prefix = 'assets/i18n/';
    var suffix = '.json';
    this.translate.useStaticFilesLoader(prefix, suffix);

    var userLang = navigator.language.split('-')[0];
    userLang = /(de|en|hr)/gi.test(userLang) ? userLang : 'en';

    this.translate.setDefaultLang('en');

    this.translate.use(userLang);
  }
 
The first two lines will define translation file locations and file extension:
 
var prefix = 'assets/i18n/';
var suffix = '.json';
this.translate.useStaticFilesLoader(prefix, suffix);
 
For this code to work we need to find current navigator language. If current language is one of three predefined (en, de, or hr) we will use it as an initial application language. If not, we’ll use English as a default one:
 
var userLang = navigator.language.split('-')[0];
userLang = /(de|en|hr)/gi.test(userLang) ? userLang : 'en';

this.translate.setDefaultLang('en');
 
If our current navigator language is one of three preconfigured, we’ll use it instead:
 
this.translate.use(userLang);
 
Open HomePage class and import ng2-translate services:
 
import {Page} from 'ionic/ionic';
import {TranslateService, TranslatePipe} from 'ng2-translate/ng2-translate';
 
We no longer need to define TranslateService provider. Once initialized in app.js it will become available to all child components/pages. You only need to add TranslatePipe pipe into the @Page decorator:
 
@Page({
  templateUrl: 'build/pages/home/home.html',
  pipes: [TranslatePipe]
})
 
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?

  • 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.

    • riccardo

      Have you solved? Can you share your solution?

  • 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?