I wrote the previous version of this article almost two years ago and I must admit not that much has changed. However, there is still enough content to validate the article update.
 
Just as in my previous article, this one will walk you through using Angular internationalization/translate library with Ionic 4. To do this we will use ngx-translate Angular library which is successor implementation of legacy Angular ng-translate module.
 
I will also showcase the most basic functionality. Hopefully, if I find the time I will also create a more advanced version of this topic.
 
 

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

 
Before we can start, make sure your Ionic 4 work environment is up and ready.
 
We will need these:
 
  • Optional – Android or iOS Environment (you can always use browser)
  • NodeJS
  • Ionic 4
  • Cordova
 
If you do not have a preconfigured Ionic working environment follow the tutorial here: Ionic 4 | Installation Guide.
 

1. Update Ionic CLI

 
If you do not have Ionic and/or Cordova install them like this:
 
npm install -g ionic cordova
 
If you only need to update:
 
npm update -g ionic cordova
 
 

2. Create A New Project

 
ionic start IonicInternationalizationV2 blank
cd IonicInternationalizationV2 
 
You will find a working example at the end of this article, however, if you want to learn how this implementation works, keep reading further. Jump to the working example here.
 
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

 
For this example we only need a browser of your choice:
ionic cordova platform add browser
 
If you prefer the Android platform:
 
ionic cordova platform add android
 
Mac users can also add iOS platform:
 
ionic cordova platform add ios
 

4. Install ngx-translate library

 
We need these for our walk-through:
 
npm install @ngx-translate/core @ngx-translate/http-loader@latest rxjs --save
 
The @ngx-translate/core holds the basic implementation for the translation process, including some pipes. The @ngx-translate/http-loader loads the json translation files from availably file system

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’s 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 (the previous statement is no longer true, in the below example you will find how to deploy translations in any other folder). 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"
	}
}
 
Next, we need to import the necessary modules in app.module.ts:
 
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {HttpClient, HttpClientModule} from '@angular/common/http';
 
Don’t forget to include HttpClientModule and TranslateModule like this:
 
HttpClientModule,
TranslateModule.forRoot({
	loader: {
		provide: TranslateLoader,
		useFactory: HttpFactory,
		deps: [HttpClient]
	}
})],
 
or for a better idea:
 
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

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

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, 
            IonicModule.forRoot(), 
            AppRoutingModule, 
	        HttpClientModule,
	        TranslateModule.forRoot({
	            loader: {
	                provide: TranslateLoader,
	                useFactory: HttpFactory,
	                deps: [HttpClient]
	            }
	        })],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

// important for "ahead of time" compilation
export function HttpFactory(http: HttpClient) {
    return new TranslateHttpLoader(http);

    /* If you want to change the default translations folder do it like this */

    //return new TranslateHttpLoader(http, './assets/i18mnh/', '.json');
}
 
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 platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private translateService: TranslateService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.translateService.setDefaultLang('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.
 
One last thing, we also need to import TranslateModule into every page module. In our case it’s home.module.ts:
 
import { TranslateModule } from '@ngx-translate/core';

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

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    TranslateModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ])
  ],
  declarations: [HomePage]
})
export class HomePageModule {}
 
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-header>
	<ion-toolbar>
		<ion-title>{{ 'PAGE_TITLE' | translate }}</ion-title>
	</ion-toolbar>
</ion-header>

<ion-content>
	<ion-segment (ionChange)="segmentChanged($event)">
		<ion-segment-button checked value="en" color="primary">
			<ion-label>{{ 'BUTTONS.btn_eng' | translate }}</ion-label>
		</ion-segment-button>
		<ion-segment-button value="hr">
			<ion-label>{{ 'BUTTONS.btn_cro' | translate }}</ion-label>
		</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