Pourquoi Internationalisation (i18n) avec Angular ?
L'Internationalisation (i18n) est un processus crucial pour les développeurs web modernes. Il permet aux applications de fonctionner dans différents langues et régions, en s'assurant que le contenu soit adapté aux conventions culturelles et linguistiques locales. Dans un monde globalisé où de plus en plus d'utilisateurs sont multilingues, une application bien internationalisée offre une meilleure expérience utilisateur et augmente sa visibilité sur les marchés mondiaux.
Un cas concret est l'application d'un site e-commerce qui doit être accessible à des clients dans différents pays. Par exemple, un produit peut avoir des noms et des descriptions différentes en français et en anglais. L'i18n permet de gérer ces traductions facilement et de les mettre à jour de manière cohérente.
Prerequis
- Connaissance de base d'Angular
- Angular CLI installé (v12+)
- Node.js et npm installés (v14+)
- Un éditeur de code comme Visual Studio Code
Concepts fondamentaux
1. i18n et l10n
- i18n stands for "Internationalization" and is the process of designing an application so that it can be localized for different languages and regions.
- l10n stands for "Localization," which is the process of adapting content to meet the specific requirements of a target language and culture.
2. ngx-translate
ngx-translate est une bibliothèque populaire pour la gestion des traductions dans Angular applications. Elle permet de gérer les fichiers de traduction, d'interpoler du texte et de charger dynamiquement le contenu en fonction de la langue courante.
npm install @ngx-translate/core @ngx-translate/http-loader --save
3. Fichiers de Traduction
Les fichiers de traduction sont des fichiers JSON qui contiennent les traductions pour chaque clé. Par exemple :
src/assets/i18n/en.json
{
"HELLO": "Hello",
"WELCOME": "Welcome to our app"
}
src/assets/i18n/fr.json
{
"HELLO": "Bonjour",
"WELCOME": "Bienvenue dans notre application"
}
4. Configuration de ngx-translate
Ajoutez les configurations nécessaires au fichier app.module.ts :
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
declarations: [
AppComponent,
// autres composants
],
imports: [
BrowserModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
5. Utilisation des Traductions
Vous pouvez maintenant utiliser les traductions dans vos composants. Par exemple :
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = this.translate.instant('HELLO');
constructor(private translate: TranslateService) {
this.translate.setDefaultLang('en'); // définir la langue par défaut
this.translate.use('fr'); // changer la langue à 'fr'
}
}
html
<!-- app.component.html -->
<div>
<h1>title</h1>
</div>
<button (click)="changeLanguage('en')">English</button>
<button (click)="changeLanguage('fr')">Français</button>
<!-- Utilisation de la directive i18n dans le template -->
<p i18n>Click the buttons to switch languages.</p>
6. Changement de Langue Dynamique
Vous pouvez changer dynamiquement la langue de l'application en utilisant le service TranslateService :
changeLanguage(lang: string) {
this.translate.use(lang);
}
Mise en pratique : projet fil rouge
Nous allons construire un petit application Angular qui permet d'afficher des articles dans différentes langues.
Étape 1 : Créer le Projet
ng new multilingual-app --strict
cd multilingual-app
Étape 2 : Ajouter ngx-translate
npm install @ngx-translate/core @ngx-translate/http-loader --save
Étape 3 : Configurer ngx-translate
Ajoutez les configurations nécessaires au fichier app.module.ts :
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
declarations: [
AppComponent,
ArticleComponent
],
imports: [
BrowserModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Étape 4 : Créer le Composant ArticleComponent
ng generate component article
Modifier article.component.ts :
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.css']
})
export class ArticleComponent implements OnInit {
articleTitle = this.translate.instant('ARTICLE.TITLE');
articleContent = this.translate.instant('ARTICLE.CONTENT');
constructor(private translate: TranslateService) { }
ngOnInit(): void {
this.translate.setDefaultLang('en'); // définir la langue par défaut
}
}
Modifier article.component.html :
<div>
<h2>articleTitle</h2>
<p>articleContent</p>
</div>
<button (click)="changeLanguage('en')">English</button>
<button (click)="changeLanguage('fr')">Français</button>
<!-- Utilisation de la directive i18n dans le template -->
<p i18n>Click the buttons to switch languages.</p>
Étape 5 : Ajouter les Fichiers de Traduction
Créez les fichiers src/assets/i18n/en.json et src/assets/i18n/fr.json :
src/assets/i18n/en.json
{
"ARTICLE": {
"TITLE": "My Article",
"CONTENT": "This is the content of my article."
}
}
src/assets/i18n/fr.json
{
"ARTICLE": {
"TITLE": "Mon Article",
"CONTENT": "Ceci est le contenu de mon article."
}
}
Étape 6 : Ajouter le Composant ArticleComponent au Template de AppComponent
Modifier app.component.html :
<app-article></app-article>
Erreurs frequentes et debugging
Erreur 1 : Traduction non trouvée
Code incorrect
this.articleTitle = this.translate.instant('ARTICLE.TITLE');
Code correct
this.articleTitle = this.translate.get('ARTICLE.TITLE').subscribe((translation: string) => {
this.articleTitle = translation;
});
Erreur 2 : Langue par défaut non définie
Code incorrect
this.translate.setDefaultLang('fr');
Code correct
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
declarations: [
AppComponent,
ArticleComponent
],
imports: [
BrowserModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
this.translate.setDefaultLang('en');
Erreur 3 : Changement de langue non pris en compte
Code incorrect
changeLanguage(lang: string) {
this.translate.use(lang);
}
Code correct
changeLanguage(lang: string) {
this.translate.use(lang).subscribe(() => {
// action à effectuer après le changement de langue
});
}
Pour aller plus loin
- Gestion des Plurales et Dates : Découvrez comment gérer les pluriels et les dates dans les traductions avec
ngx-translate. - Utilisation de Pipes personnalisés : Créez des pipes pour formater du texte en fonction de la langue.
- Intégration avec des services backend : Apprenez à charger les fichiers de traduction depuis un service backend.
Défi pratique
Créez une application Angular qui permet d'afficher des informations sur différents pays, comme le nom, la capitale et la population. Utilisez l'i18n pour afficher ces informations en différentes langues.