Ionic Angular Tutorial: Multilanguage App using Angular i18n

by Didin J. on Mar 03, 2023 Ionic Angular Tutorial: Multilanguage App using Angular i18n

A comprehensive step-by-step Ionic Angular tutorial on creating multilanguage mobile apps using Angular Internationalization (i18n)

This Ionic Angular tutorial will show you how to create multilanguage mobile apps using Angular Internationalization (i18n). In the mobile apps will be a choice between languages or using the default device language. This time we will use 3 different languages for this application. They are English, Spanish, and Arabic.

This tutorial is divided into several steps:

The following tools, frameworks, and modules are required for this tutorial:

  1. Node.js (with NPM or Yarn)
  2. Ionic CLI
  3. Angular
  4. Angular Translate Module
  5. Terminal or Node Command Line
  6. IDE or Text Editor

Before starting the main steps, make sure you have installed Node.js and can run NPM. To check the installed Node.js (NPM or Yarn) type these commands from the Terminal or Node command line.

node -v
v18.14.0
npm -v
9.5.0

Let's get started with the main steps!


Step #1: Create Ionic Angular Apps

We will use Ionic CLI to create Ionic with the Angular project or application. Type this command to install the latest Ionic application.

npm install -g @ionic/cli

To create a new Ionic with Angular and Tabs mode, type this command.

ionic start ionicMultiLang tabs --type=angular

Leave all questions as default then wait for all required Node modules to be installed. To working this Ionic Angular app, open this project with your IDE or Text Editor.

cd ionicMultiLang
code .

To run this application for the first time, type this command.

ionic serve -l

Install the @ionic/lab module if it's required to run as the lab in the browser. Here is, what the Ionic Angular application looks like.

Ionic Angular Tutorial: Multilanguage App using Angular i18n - tabs


Step #2: Install the Required Dependencies

To make multilanguage work, we just install the Angular translate module or dependencies. For that, type these commands to install them.

npm install @ngx-translate/core
npm install @ngx-translate/http-loader

Next, open and edit `src/app/app.modules.ts` then add these imports.

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

Add this export after all imports to load TranslateHttpLoader from the JSON files that contain all words in different languages.

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

Add TranslateModule to the @NgModule imports block.

@NgModule({
  ...
  imports: [
    ...
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      }
    })
  ],
  ...
})

We will create the i18n folder and JSON files later.


Step #3: Create the Languages JSON files

As we mention in the first paragraph, we will use 3 different languages. For that, we will need 3 JSON files for each language. First, create a new folder inside the assets folder.

mkdir src\assets\i18n

Add these JSON files to that folder.

en.json
es.json
ar.json

Open and edit en.json then add these keys and values of words in English.

{
  "HOME": "Home",
  "CONTENT": "Content",
  "ABOUT": "About",
  "HELLO": "Hello",
  "WELCOME": "Welcome to the multilanguage Ionic app",
  "SIMPLE_APP": "This is just a simple app",
  "MY_NAME": "My name is Bill Musk"
}

Open and edit es.json then add these keys and values of words in Spanish.

{
  "HOME": "Hogar",
  "CONTENT": "Contenido",
  "ABOUT": "Sobre",
  "HELLO": "Hola",
  "WELCOME": "Bienvenido a la aplicación multilenguaje de Ionic",
  "SIMPLE_APP": "Esta es solo una aplicación simple.",
  "MY_NAME": "Mi nombre es bill almizcle"
}

Open and edit ar.json then add these keys and values of words in Arabic.

{
    "HOME": "????",
    "CONTENT": "?????",
    "ABOUT": "???",
    "HELLO": "??????",
    "WELCOME": "?????? ?? ?? ????? Ionic ????? ??????",
    "SIMPLE_APP": "??? ???? ????? ????",
    "MY_NAME": "???? ??? ????"
}


Step #4: Create a Translate Config Service

We need a service to get the default, get current, and set language to these Ionic apps. For that, create a new Typescript file src\app\translate-config.service.ts. Then add these imports.

import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

Then add this @Injectable with the class name TranslateConfigService and the body of the class like this.

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

  currentLang: any;

  constructor(
    private translate: TranslateService,
  ) {
    this.currentLang = localStorage.getItem('lang');
  }

  getDefaultLanguage(){
    if (this.currentLang) {
      this.translate.setDefaultLang(this.currentLang);
    } else {
      localStorage.setItem('lang', this.translate.getBrowserLang()!);
      this.currentLang = this.translate.getBrowserLang();
      this.translate.setDefaultLang(this.currentLang);
    }
    return this.currentLang;
  }

  setLanguage(setLang: string) {
    this.translate.use(setLang);
    localStorage.setItem('lang', setLang);
  }

  getCurrentLang() {
    return localStorage.getItem('lang');
  }

}

The code above started by loading the current language from the local storage. The function gets the default language used to check if existing language exists in the local storage otherwise gets the browser or device language. The set language function set the language to the local storage. The get current language function only get language from the local storage.


Step #5: Implement Multilanguage in the View

We will use the multi-language in the existing tabs with the selector in the header bar. First, open and edit `src\app\tabs\tabs.module.ts` then add this import.

import { TranslateModule } from '@ngx-translate/core';

Add the translate module to the @NgModule imports.

@NgModule({
  imports: [
    ...
    TranslateModule
  ],
  ...
})

Next, open and edit `src\app\tabs\tabs.page.ts` then add these imports.

import { TranslateConfigService } from 'src/app/translate-config.service';
import { TranslateService } from '@ngx-translate/core';

Add a variable to hold the current language.

language: any;

Add arguments and implementation to the constructor.

  constructor(private translateConfigService: TranslateConfigService, private translate: TranslateService) {
    this.translateConfigService.getDefaultLanguage();
    this.language = this.translateConfigService.getCurrentLang();
  }

Next, open and edit `src\app\tabs\tabs.page.html` then replace all HTML tags with this.

<ion-tabs>

  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="tab1">
      <ion-icon name="triangle"></ion-icon>
      <ion-label>{{"HOME" | translate}}</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab2">
      <ion-icon name="ellipse"></ion-icon>
      <ion-label>{{"CONTENT" | translate}}</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab3">
      <ion-icon name="square"></ion-icon>
      <ion-label>{{"ABOUT" | translate}}</ion-label>
    </ion-tab-button>
  </ion-tab-bar>

</ion-tabs>

Next, to implement the select language button in the toolbar, open and edit `src\app\tab1\tab1.module.ts` then add these imports.

import { TranslateModule } from '@ngx-translate/core';

Add the translate module to the @NgModule imports.

@NgModule({
  imports: [
    ...
    TranslateModule
  ],
  ...
})

Next, open and edit `src\app\tab1\tab1.page.ts` then add these imports.

import { TranslateConfigService } from 'src/app/translate-config.service';
import { TranslateService } from '@ngx-translate/core';
import { ActionSheetController } from '@ionic/angular';

Add a variable to hold the current language.

language: any;

Add arguments and implementation to the constructor.

  constructor(
    private translateConfigService: TranslateConfigService,
    public actionSheetController: ActionSheetController) {
    this.translateConfigService.getDefaultLanguage();
    this.language = this.translateConfigService.getCurrentLang();
  }

Add a function to switch between the languages.

  async changeLanguage() {
    const actionSheet = await this.actionSheetController.create({
      header: 'Languages',
      buttons: [{
        text: 'English',
        icon: 'language-outline',
        handler: () => {
          this.language = 'en';
          this.translateConfigService.setLanguage('en');
        }
      }, {
        text: 'Spanish',
        icon: 'language-outline',
        handler: () => {
          this.language = 'es';
          this.translateConfigService.setLanguage('es');
        }
      }, {
        text: 'Arabic',
        icon: 'language-outline',
        handler: () => {
          this.language = 'ar';
          this.translateConfigService.setLanguage('ar');
        }
      }, {
        text: 'Cancel',
        icon: 'close',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();

    const { role, data } = await actionSheet.onDidDismiss();
    console.log('onDidDismiss resolved with role and data', role, data);
  }

Next, open and edit `src\app\tab1\tab1.page.html` then replace all HTML tags with this.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      {{"HOME" | translate}}
    </ion-title>
    <ion-buttons slot="end">
      <ion-button (click)="changeLanguage()">
        <ion-icon name="language-outline"></ion-icon>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">{{"HELLO" | translate}}</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-card>
    <ion-card-content>
      {{"WELCOME" | translate}}
    </ion-card-content>
  </ion-card>
</ion-content>

Next, do the same way as Tab 1 to Tab 2 and 3 except for the HTML. The `src\app\tab2\tab2.page.html` should look like this.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      {{"CONTENT" | translate}}
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">{{"ABOUT" | translate}}</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-card>
    <ion-card-content>
      {{"SIMPLE_APP" | translate}}
    </ion-card-content>
  </ion-card>
</ion-content>

The `src\app\tab3\tab3.page.html` should look like this.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      {{"ABOUT" | translate}}
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">{{"HELLO" | translate}}</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-card>
    <ion-card-content>
      {{"MY_NAME" | translate}}
    </ion-card-content>
  </ion-card>
</ion-content>


Step #6: Run and Test Ionic Angular Apps

Now, we will run and test this application on an Android device or simulator. Type this command to build the Ionic Capacitor Android application.

ionic capacitor build android --prod

The Android Studio will be opened automatically. Wait for Gradle to download all dependencies then select the device from the toolbar. Click the play button in the toolbar and here is the Ionic Multilanguage App on Android.

Ionic Angular Tutorial: Multilanguage App using Angular i18n - demo

That it's, the Ionic Angular Multilanguage App using Angular i18n. You can get the full source code from our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 6 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:

Thanks!

Loading…