Lejdi Prifti

0 %
Lejdi Prifti
Software Engineer
Web3 Developer
ML Practitioner
  • Residence:
    Albania
  • City:
    Tirana
  • Email:
    info@lejdiprifti.com
English
Italian
French
Spring
React & Angular
Machine Learning
Docker & Kubernetes
AWS & Cloud
Team Player
Communication
Time Management
  • Java, JavaScript, Python
  • AWS, Kubernetes, Azure
  • Bootstrap, Materialize
  • Css, Sass, Less
  • Blockchain, Ethereum, Solidity
  • React, React Native, Flutter
  • GIT knowledge
  • Machine Learning, Deep Learning
0

No products in the basket.

Configure i18n in Angular 17

20. May 2024

Overview

In this brief tutorial, I’ll walk you through the process of implementing internationalization (i18n) with Angular 17. As for my personal preference, I find json files to be cleaner and easily understandable. That’s why I prefer to use the library @ngx-translate/core in conjuction with the HTTP loader @ngx-translate/http-loader .

Table of Contents

Project setup

For this tutorial, I will setup a simple Angular 17 project named angular-i18n using the ng command. 

				
					ng new angular-i18n
				
			

Installation

It is now necessary for us to install our favorite translation libraries. Remember that a professional project always requires internationalization (i18n) in it.

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

Configuration

Until now, it has been quick and easy. Let’s configure everything and make it work.

I prefer to organize all configuration files into a folder named config followed by the name of the feature. At the end, the folder tree looks like app/core/config/i18n. In this final folder, I am going to create a file named translate-loader.config.ts.

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

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

export function provideTranslation() {
    return {
        defaultLanguage: 'en',
        loader: {
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [HttpClient]
        },
    }
}
				
			

Let’s break down the code that we wrote above.

createTranslateLoader function takes an HttpClient instance as a parameter and returns on the other hand TranslateHttpLoader instance. The TranslateHttpLoader is used to load translation files from the application’s assets folder. The path to the assets folder is specified in the function as ./assets/i18n/. The file extension for translation files is also specified as .json.

Translation files

Since we are here, we can go to the assets folder and create the i18n folder with two files. We are going to add the en.json which will hold the labels in English and the it.json which will hold the labels in Italian.  

				
					{
    "title": "Your app is running with i18n enabled."
}
				
			
Providing translation

Overall, provideTranslation function defines a configuration object used by the @ngx-translate library.

The defaultLanguage property specifies the default language of the application, which is ‘en’ (English) in this case.

Additionally, the loader property provides a factory function (useFactory) that creates a TranslateHttpLoader instance using the createTranslateLoader function we defined earlier. It also specifies that the HttpClient dependency should be injected into the factory function. 

We have defined the functions but we have not configured the application to use them yet. To do it, we must go to the app.config.ts file and add the new providers.

				
					import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';

import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
import { provideTranslation } from './core/config/i18n/translate-loader.config';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    importProvidersFrom(TranslateModule.forRoot(provideTranslation())),
    provideHttpClient(),
  ]
};

				
			

We import the TranslateModule from @ngx-translate/core and call its forRoot method. This method is used to configure the library at the application level. The method provideTranslation() injects the necessary configurations into the TranslateModule.

Finally, we use the importProvidersFrom to import the providers as the method says. A great example of clean code!

It is very important to provide the HttpClient service from @angular/common/http. This service is used to make HTTP requests, which is needed for loading translation files.

Usage

It’s time to use the translation. I changed a little bit the content of the app.component.html file. I expect the title to get translated. 

				
					<p>Congratulations! {{ 'title' | translate }} 🎉</p>
				
			

I also added again into the app.component.html file a select to demonstrate the change of language.

				
					 <select [(ngModel)]="selectedLanguage" (change)="onLanguageChange()">
        <option value="en">English</option>
        <option value="it">Italian</option>
      </select>
				
			

Finally, in the app.component.ts file I import the TranslateModule which is highly important to make the translate pipe work and also use the TranslateService to change the language when needed.

				
					import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterOutlet } from '@angular/router';
import { TranslateModule, TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, TranslateModule, FormsModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent {
  title = 'angular-i18n';
  selectedLanguage = 'en';

  constructor(private translateService: TranslateService){}

  onLanguageChange() {
    this.translateService.use(this.selectedLanguage)
  }

}
				
			

Results

That’s how you implement internationalization (i18n) in Angular 17. 

Checkout the blog for more similar content.

Happy coding!

Posted in AngularTags:
3 Comments
  • youssef

    Hey, good blog, say I changed the language to ‘FR’ (french) and then refreshed the page, will the langugae ‘FR’ stay or will it default to ‘EN’?

    16:21 27. June 2024 Reply
    • Hi and thank you for your comment!

      If you use the current implementation described in this article, the page will default to ‘EN’ because it does not have persistence. If you implement persistency, so that the language at initialization is read from local storage or cookies, then you can guarantee that on page reload the language sticks.

      12:34 29. June 2024 Reply
  • […] In the project I’m developing for a client, I use toasts to inform users about potential issues when the backend API is called. For every known exception thrown, the backend responds with an object containing a code and a message. This code maps to the frontend, and a translation service displays it in different languages. If you want to learn how to integrate a translation service into your Angular 17 application, have a look at this easy-to-follow tutorial. […]

    14:45 14. July 2024 Reply
Write a comment
Receive the latest articles

Subscribe To My Weekly Newsletter

Get insights, practical tips, and career advice to advance your skills and stay ahead in the tech industry.