Ionic 4 | Adding Multi Language Translation Feature in Ionic Application using ngx-translate

Mobile applications are built for a wide audience and different countries, so it’s sometimes become important to present your application to people in their local language.

In this post, we will talk about a powerful library popularly known as nxg-translate. Application text content can be translated into languages which are selected and have related JSON files in the assets folder.

How does the language translation work in an Ionic application?

Text content in the application needs to be translated into different languages by the developer and kept in JSON files, for example, English text will be available in en.json and the French language in a fr.json file. These files will be called by nxg-translate and language text will be rendered by a simple method very easily.

Start Implementation

Here we will create an Ionic 4 application which will get Browser language by default then provide radio selection to switch between languages.

Create an Ionic Application

Let’s create a new Ionic application using Ionic CLI and also a languageConfig service todo have translation related methods at one place.

# Create a new Ionic app with a blank template
$ ionic start Ionic4Translate blank
$ cd Ionic4Translate

# Create Service without test files
$ ionic generate service translateConfig --skipTests=true

Install Language Translation library

Run following npm commands to install the library in the application

$ npm i @ngx-translate/core @ngx-translate/http-loader

Make changes in app.module.file to import translation library and HttpClientModule to load json language files.

//app.module.ts
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 { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { TranslateConfigService } from './translate-config.service';

export function LanguageLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}

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

 

Next, we need to create JSON translation files at this 'assets/i18n/' location

en.json

{
    "HOME": {
        "title": "Ionic 4 Multi Language Translation",
        "text": "This is random text to show translation in application"
    }
}

ko.json

{
    "HOME": {
        "title": "ν™ˆμ— μ˜€μ‹  것을 ν™˜μ˜ν•©λ‹ˆλ‹€.",
        "text": "이것은 μ‘μš© ν”„λ‘œκ·Έλž¨μ—μ„œ λ²ˆμ—­μ„ λ³΄μ—¬μ£ΌλŠ” μž„μ˜μ˜ ν…μŠ€νŠΈμž…λ‹ˆλ‹€"
    }
}

 

Now open the translate-config.service.ts file which we create on the start of the tutorial the add methods to get browser default language and a method to set the language by user action.

//translate-config.service.ts
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Injectable({
  providedIn: 'root'
})
export class TranslateConfigService {

  constructor(
    private translate: TranslateService
  ) { }

  getDefaultLanguage(){
    let language = this.translate.getBrowserLang();
    this.translate.setDefaultLang(language);
    return language;
  }

  setLanguage(setLang) {
    this.translate.use(setLang);
  }

}

In getDefaultLanguage() method we are calling library's getBrowserLang() method to get device default language.

setLanguage() method will be called by user action to load a specific JSON file to change application text. The use method can be called to change language at any time.

Finally, we are ready to implement the language translation feature on our Home page of the application.

In home.page.html replace the following code with radio selection of a language. Data from JSON files are displayed using translate pipe filter as shown below.

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic 4 Multi Language Translation
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>


  <ion-list>
    <ion-item>
      <ion-label>Select Language</ion-label>
      <ion-select placeholder="Select One" [(ngModel)]="selectedLanguage" (ionChange)="languageChanged()">
        <ion-select-option value="en">English</ion-select-option>
        <ion-select-option value="ko">Korean</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>


  {{ 'HOME.text' | translate:params }}


</ion-content>

In home.page.ts file, we will call a getDefaultLanguage method in our service then call the setLanguage method on radio selection.

//home.page.ts
import { Component } from '@angular/core';
import { TranslateConfigService } from '../translate-config.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  selectedLanguage:string;

  constructor(private translateConfigService: TranslateConfigService){
    this.selectedLanguage = this.translateConfigService.getDefaultLanguage();
  }

  languageChanged(){
    this.translateConfigService.setLanguage(this.selectedLanguage);
  }

}

That's it now you only need to add more JSON file similar to that for more language options for users to select.

Subscribe
Notify of
guest
10 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Augustine

Thanks man.

ashish

i am trying to translate my app english to nepali language so in ne.json is language is auto generate?

Chetan

i am getting the below error please check and resolve i have done all the thinks same as your tutorial.

ERROR Error: Uncaught (in promise): TypeError: this.languageService.getDefaultLanguage is not a function
TypeError: this.languageService.getDefaultLanguage is not a function

Luiz Antonio Jr

What about the splash screen? Didnt find any article to show an unique splashscreen according to user mobile language

vinod CH

do i need to keep english.json ???

because i created one app with three languages so when I stared it works fine with three languages (link Telugu, Hindi, and English) but i didn’t create en.json just created two JSON files (Telugu and Hindi ) in the app but it worked fine after one month I tried to build that app now English is not working I don’t know why? any idea

Squapl Magazine

thanks for the tutorial. works great

Moises

Thanx a lot πŸ˜€