Jalan Technologies > Blog >

Introduction to Internationalization i18n

This step-by-step guide explores the successful implementation of multi-language Angular applications rendered server-side. It introduces internationalization (i18n) in Angular, explaining its significance and the differences between i18n and localization (l10n). The guide details how Angular can internationalize your app, from displaying numbers and marking text for translation to enabling language switching.

This blog is a step by step guide for successful implementation of multi language angular applications rendered server side.

I realized that I needed to implement internationalization i18n when a user from another country wasn’t able to understand the language of my company’s website because it was loading with English fonts – a language he does not speak.

Their browser renders the website in the English language. So for making the website to load as per the Country/Region specifically, I enabled angular internationalization (i18n) in my website.

So let’s see what angular internationalization i18n is and how you can use it in your angular applications.

What Is The Meaning of Internationalization i18n?

Internationalization i18n is the process of designing and developing products, content or application softwares to be adaptable and accessible to people from different regions and cultures. It allows making changes to accommodate various languages, date formats, and cultural variations, ensuring a more global and inclusive user experience to your target audience.

                                                                                                          OR

Internationalization i18n is the designing of your website or app in such a way where it is easy to understand in various locales around the world. You can understand the term “Locale” as a region where people speak a specific language.

What Is i18n Angular?

 I18n refers to the process of internationalization in Angular, denoted as “i18n” for the 18 letters between “i” and “n” in the word, which involves adapting an application to support multiple languages and regions for a global audience.

What is Localization L10n in Angular?

Localization L10n in Angular is the process of customizing a web application to match the language, cultural, and regional preferences of a specific audience or locale. It ensures that users from different regions can interact with the app in their preferred language and with contextually relevant content.

What Does l10n Mean?

L10n is short for “localization.” It’s a term used in the context of adapting content, software, or products to suit specific regional or cultural preferences. The “10” represents the number of letters between “l” and “n” in the word “localization l10n.”

How Angular Internationalize Your App?

  1. Angular displays numbers ( currencies, percentages , dates ) in a local format.
  2. Marking text in component templates for translation
  3. Marking plural forms of expressions for translation
  4. Marking alternate text for translation

Angular empowers applications to cater to the diverse requirements of various regions or locales, consequently facilitating localization l10n, abbreviated as l10n. Also through i18n, we can effectively adapt all web projects across the array of applications, making the internet accessible to a global audience.

Let’s start the angular internationalization i18n tutorial on how we can add support for multiple languages on our website.

Angular i18n Support

With Angular CLI commands you can create blank Angular applications for the experiments.

Prerequisites

At least two simple language files in JSON format (to test that the application switches languages at runtime.)

In the src/assets folder create a new i18n subfolder and put the following en.json file inside:

{ “TITLE”: “My i18n Application (en)” }

This will serve as our default “English” locale. Afterward, proceed to generate a new file within the i18n subfolder, in the name of ua.json.

{ “TITLE”: “My i18n Application (ua)” }

Now you’ll notice, your application will dynamically translate its title into various languages. For an easy approach, I’m using a single string and appending the locale name to it for both languages.

Translation Service

We now require a dedicated Angular Service to centrally manage translations for the entire application.

ng g service translate --module=app.

Our service must retrieve the relevant translation file from the src/assets directory. To achieve this, we should:

Configure the HTTP client and the associated module for the application.

Enhance the newly created service by introducing a data property to store the translation strings.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class TranslateService {
data: any = {};
constructor(private http: HttpClient) {}
}

You also need to update the main application module to import the HTTP Client  Module.

import { HttpClientModule } from '@angular/common/http';
import { TranslateService } from './translate.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
TranslateService
],
...
})
export class AppModule { }

At this juncture, our HTTP stack is prepared, and we should be capable of fetching translation files.

Basic translation loading

Now, let’s implement a ‘use(lang)’ method in the service to trigger the download of the files and facilitate language switching.

@Injectable()
export class TranslateService {
data: any = {};
constructor(private http: HttpClient) {}
use(lang: string): Promise<{}> {
return new Promise<{}>((resolve, reject) => {
const langPath = `assets/i18n/${lang || 'en'}.json`;
this.http.get<{}>(langPath).subscribe(
translation => {
this.data = Object.assign({}, translation || {});
resolve(this.data);
},
error => {
this.data = {};
resolve(this.data);
}
);
});
}
}

The implementation provided above is a streamlined approach to fetching translations.

Upon every call, the service goes to the assets/il8n folder and gets the corresponding file.

Testing The Service

It is now time to test the service to ensure it is working properly and to check if it can load the translation file.

You need to                                                                                                                              

  1. Inject the Translate Service instance into the class constructor
  2. Invoke the use(‘en’) method
  3. Output the obtained data to the console.
  4. Modify the primary application component class as demonstrated in the following example:
import { Component } from '@angular/core';
import { TranslateService } from './translate.service';
@Component({...})
export class AppComponent {
constructor(private translate: TranslateService) {
translate.use('en').then(() => {
console.log(translate.data);
});
}
}

When you execute your application using the ‘ng serve –open’ command and inspect it in Chrome Developer Tools, you can expect to observe the following output:

Loading Locales Before The Application Starts

Usually, it’s advisable to have at least the default locale available when the application starts. As it helps prevent any “flickering” effects where users might see resource keys before the respective translations have finished loading.

Angular offers the APP_INITIALIZER token, which enables us to set up and configure our providers before the application begins.

Below is an example implementation that allows us to load and set en.jsonas the default application language:

import { NgModule, APP_INITIALIZER } from '@angular/core';
export function setupTranslateFactory(
service: TranslateService): Function {
return () => service.use('en');
}
@NgModule({
...

providers: [
TranslateService,
{
provide: APP_INITIALIZER,
useFactory: setupTranslateFactory,
deps: [ TranslateService ],
multi: true
}
],

...
})
export class AppModule { }

Let’s now test this in action. Return to the ‘app.component.ts’ file and delete the explicit ‘use(‘en’)’ invocation. Leave just logging to console output as shown in the next example:

@Component({...})
export class AppComponent {
constructor(private translate: TranslateService) {
console.log(translate.data);
}
}

If you want to launch the application now (or refresh the page if it’s already running), the console output should remain the same as previous time.

Keep in mind, that this time, the service initializes before the application component, allowing us to access the language data without the need for additional calls.

Let’s now move on to content translation.

Translation Pipe

Making use of translation pipes for translation is a common approach in the Angular world. We will be adopting the following syntax for translating content in our components: 

<element>{{ 'KEY' | translate }}</element>
<element title="{{ 'KEY' | translate }}"></element>
<element [title]="property | translate"></element>

Use the following Angular CLI command to create a new  TranslatePipe fast:

ng g pipe translate --module=app

As the translation data has already been loaded and is stored within the TranslateService, our pipe can easily access the service and retrieve the appropriate translation using the provided key.

import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from './translate.service';
@Pipe({
name: 'translate',
pure: false
})
export class TranslatePipe implements PipeTransform {
constructor(private translate: TranslateService) {}
transform(key: any): any {
return this.translate.data[key] || key;
}
}

The implementation described above is foundational, showcasing the initial approach. In this blog, we’re using only a single level of object properties. However, you can expand upon this code in the future to support property paths, such as ‘SOME.PROPERTY.KEY,’ and enable traversal of translation objects.

Now it’s time for ….

Testing The Pipe

It is now time to test the pipe in action and see if it is working as per the expectations.

You need to                                                                                                                              

Update the auto-generated application template app.component.html

Substitute the title element with the following code block:

<h1>
Welcome to {{ 'TITLE' | translate }}!
</h1>

Switch to the currently running application, and you should notice that the title value now mirrors the content of the ‘en.json’ file.

If the browser language changes, the value will reflect the content of the different JSON files as per the region specifically. We can add as many as languages through which we can display our website fonts.

What’s the biggest thing you’re struggling with right now that we as a technology consulting company can help you with? Feel free to Contact us. We hope our assistance will help!

Disclaimer: The statements and opinions expressed in this article are those of the author(s) and do not necessarily reflect the positions of Jalan Technologies.

Table of Contents

Hire Our Development Experts.




    Want to raise the bar for your organization?

    Subscribe to our newsletter to receive latest insights on how technology can help turn your goals into reality. By subscribing, you’ll get access to thought-provoking articles, case studies, and resources to help accelerate your impact.

    Get the latest updates straight to your inbox

      Related Blogs
      technology consultant
      Business Insights
      All you need to know about technology consultant

      Technology consultant experts like Jalan Technologies, empowers businesses to strategically leverage technology for success. Services encompass strategic planning, system integration,

      Scroll to Top

      Subscribe Now

        Never Miss Another Post