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
 
 

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



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