Internationalization of a simple angular app

Internationalization of a simple angular app

I am writing this article because I spent more time looking and struggling to find a good approach to internationalize an angular application.

In this article, we will be looking at how to internationalize our simple angular apps

What is internationalization in general?

Internationalization is a process to make your application available in different languages also in different formats to display data ( such as dates, time, currency, number,...and so on.)

What is internationalization in the angular ?

Let first see what the angular official documentation says *"*Internationalization, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. Localization is the process of building versions of your project for different locales. The localization process includes the following actions.

  • Extract text for translation into different languages

  • Format data for a specific locale

A locale identifies a region in which people speak a particular language or language variant. Possible regions include countries and geographical regions. A locale determines the formatting and parsing of the following details.

  • Measurement units including date and time, numbers, and currencies

  • Translated names including time zones, languages, and countries "

I copy this on the official documentation and paste it here

Now we have seen what is internationalization and why we should need it in our angular apps, Now we are going to see how to apply it in our apps

How to apply internationalization in an angular application?

In other to apply internationalization in angular, there are various libraries that help us to internationalize our apps, let's list the popular ones among them such as: ng/localize, ngx-translate and transloco, we will not going to see all of them but we will choose the best one among them

The internationalization methods

We have two translations methods that are runtime translation and compile-time translation, let's see the difference between them

In simple terms, the main difference between runtime translation and compile-time translation in Angular relates to when the translation process takes place.

  1. Runtime Translation: In runtime translation, the translation process occurs dynamically during the execution of the application. When the application is running, Angular looks for translation files and uses them to translate the content on the fly. This means that translations are loaded and applied during the runtime, as the application is being used by the end user. Runtime translation allows for more flexibility because translations can be updated or added without recompiling the application. However, it may introduce a slight performance overhead as translations need to be loaded and applied during runtime.

  2. Compile-Time Translation: In compile-time translation, the translation process occurs during the compilation of the Angular application. The translation files are processed and incorporated into the application code before it is deployed. This means that the application is already translated and ready to use when it is deployed to the server or client's machine. Compile-time translation offers better performance because translations are already applied, and there is no need for runtime translation logic. However, if you want to update or add translations, you need to recompile the application and redeploy it.

To summarize, runtime translation allows for more flexibility in updating translations without recompiling the application, but it may introduce a slight performance overhead. On the other hand, compile-time translation offers better performance but requires recompilation and redeployment for any translation updates or additions.

Which method should i use between them?

I wonder you might ask yourself this question, I asked it myself too the first time I see these two methods, so let's see it together;

The runtime translation is recommended and performant on small and medium applications that haven't more things to translate, when we go through big applications the compile time translation is recommended, As I said, we will see together how to translate a simple angular application, as you can wonder, we will use runtime translation in our article

Internationalization implementation

Let's implement it in the code

In our example, I will show step by step how to use transloco ( the recommended library for small and medium apps ) to make our app available in different languages

Let's start by creating an angular application by running this command :

ng new internationalization-demo-app

You can replace internationalization-demo-app with other name of your choice ( it's not more than an application name ), or you can use the same as me

If they prompt you to use routing, say No, because we will not use routing in our example

Then they will prompt you to choose a style format, just choose css format and continue, it will install all the dependencies automatically, if it trains, click ctrl+c and install dependencies manually by running this command : npm install or yarn install if you are using yarn, run yarn install or yarn and wait for the installation to complete

After the installation, you can enter in your project folder ( make sure you are in the right directory, if not it will not work ) and run this command ng serve to see your application live in the browser, if you are not running other applications, your application should be run at http://localhost:4200 if you are running another app, please copy and paste the specified port in the terminal, Now you should see your app live in the browser

Let's start by implementing internationalization in our application with transloco

To use transloco, we must install it in our application by running this command :

ng add @ngneat/transloco , they will prompt you to choose the languages you will use, let's choose English and French by just writing fr, en, after you finished the installation, it will create a folder called i18n that has 2 files: fr.json ( for French translation ) and en.json ( for English translation )

That command will also add other folders and files in your project such as : transloco-root.module.ts and so on, also it should import TranslocoModule in your app.module.ts

The transloco-root.module.ts should look like this :

import { HttpClient } from '@angular/common/http';
import {
  TRANSLOCO_LOADER,
  Translation,
  TranslocoLoader,
  TRANSLOCO_CONFIG,
  translocoConfig,
  TranslocoModule
} from '@ngneat/transloco';
import { Injectable, isDevMode, NgModule } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
  constructor(private http: HttpClient) {}

  getTranslation(lang: string) {
    return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
  }
}

@NgModule({
  exports: [ TranslocoModule ],
  providers: [
    {
      provide: TRANSLOCO_CONFIG,
      useValue: translocoConfig({
        availableLangs: ['en', 'fr'],
        defaultLang: 'en',
        // Remove this option if your application
        // doesn't support changing language in runtime.
        reRenderOnLangChange: true,
        prodMode: !isDevMode(),
      })
    },
    { provide: TRANSLOCO_LOADER, useClass: TranslocoHttpLoader }
  ]
})
export class TranslocoRootModule {}

And in your app.component.ts, inject this method in other to condition the translation :

//import httpclient module
import HttpClient from @angular/common/http
//and inject it in your constructor like this
constructor(private http : HttpClient){
//
}
getTranslation(langPath: string) {
  return this.http.get(`./assets/i18n/${langPath}.json`);
}

And in your app.component.html

<div>
   <select #lang  (change)=getTranslation(lang.value)>
      <option>{{English | transloco}}</option>
      <option>{{French | transloco}}</option>
  </select>
</div>
<h1> {{Hello world, This is the angular internationalization app demo | transloco }}</h1>

Now we finish with marking words that will be translated, next let translate them into translations files

Let's start with the French translation:

In fr.json :

"English" : "Anglais ",
"French" : :Francais",
"Hello world, This is the angular internationalization app demo" : "Bonjour tout le monde, Ceci est la démo de l'application d'internationalisation angulaire"

And in en.json :

"English" : "English ",
"French" : :"French",
"Hello world, This is the angular internationalization app demo" : "Hello world, This is the angular internationalization app demo"

If you have followed all the steps, if you switch to different languages, you should see that it works well, if you switch from English to French or vice versa,

If you select the French option, you should see the texts in French like this on English option

Note that this approach is used to small and medium applications, if you are working on the large and growing app, this is not the good choice for you, your best choice would be ng/localize which offers a compile-time translation

I hope you enjoy this article, if you have any questions, please write it in the comments i will be happy to answer your questions

Thank you for reading, HAPPY CODING