In today’s expansive digital world, web developers aim to connect with a global audience. A key strategy to achieve this is to transform your Angular application into a multilingual experience. Welcome to Internationalization (i18n), where your app can communicate with users in their native languages, no matter where they are. In this blog, we’ll delve into integrating i18n into your Angular project, ensuring your app is accessible and user-friendly for people across the globe.
Introduction to Internationalization (i18n) in Angular
Imagine your web app as a bridge connecting users from around the globe. To create a welcoming and user-friendly experience for all, it’s essential to communicate in their language. Internationalization (i18n) is the key to making your app adaptable to various languages and regions. Angular offers robust tools and features to help you accomplish this.
Setting Up a New Angular Project
Before we begin our i18n journey, let’s create a new Angular project.
ng new i18n-app
You can use the following command to begin a new Angular project using the Angular CLI. During the setup process, you can configure your project, including options such as enabling Angular routing and choosing a stylesheet format (e.g., CSS, SCSS). Make sure to select the settings that match your project's requirements.
Installing and Configuring Angular’s i18n Tools
- To kickstart our i18n journey, we’ll need the right tools. We’ll install and set up Angular’s i18n tools to make our app multilingual.
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
- Once ngx-translate is installed, we can import it into our Angular module or Config and set up the translation service:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { AppComponent } from './app.component';
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
return new TranslateHttpLoader(http, '../assets/i18n/', '.json');
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
If you are using the app.config file, simply replace NgModule with the following code:
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { ApplicationConfig, importProvidersFrom } from '@angular/core';
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
return new TranslateHttpLoader(http, '../assets/i18n/', '.json');
}
export const appConfig: ApplicationConfig = {
providers: [
importProvidersFrom([
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient],
},
}),
])
]
}
In this code, we import the necessary ngx-translate modules and configure the translation loader using the HttpLoaderFactory function. The HttpLoaderFactory function uses the HttpClient module to load translation files asynchronously from the server.
Creating Translation Files
Once the translation service is set up, we can create translation files for each language we want to support. Translation files are JSON files that map keys to translated strings.
Create files with the necessary language code as the name and add translations to them.
For example, here’s an English translation file:
{
"title": "My App",
"greeting": "Hello, {{name}}!"
}
And here’s a German translation file:
{
"title": "Meine App",
"greeting": "Hallo, {{name}}!"
}
Here is the folder structure and the names of the files.
Note: The translation files utilize the same keys but with different values for each language. This simplifies switching between languages in our application without modifying the code.
Using Translations in Templates
With our translation files ready, we can now integrate them into our Angular templates. The first step is to inject the translation service into our component:
App.component.ts :
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 {
constructor(private translate: TranslateService) {
// Set the default language
translate.setDefaultLang('EN');
}
translateLanguage(lang: string) {
// Set the current language
this.translate.use(lang);
}
}
In this code, we inject the TranslateService into our component and set English as the default language. We also define a translateLanguage method that allows us to change the application's language.
Create a component For Language Translation
ng g c LanguageTranslation
After creating the component, we can utilize the Translation Service to translate between multiple languages.
LanguageTranslation.component.ts
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-language-translator'
})
export class LanguageTranslationComponent {
constructor(private translate: TranslateService) {}
TranslateToEnglish() {
this.translate.use('En');
}
TranslateToGerman() {
this.translate.use('DE');
}
}
LanguageTranslation.component.html
<p>{{ "title" | translate }}</p>
<div>
<button (click)="translateToEnglish()">English</button>
<button (click)="translateToGerman()">German</button>
</div>
In this code, we create a LanguageTranslationComponent that injects the TranslateService and provides two buttons to switch between English and German. When a button is clicked, we call the translateLanguage method on the TranslateService with the appropriate language code.
Note: When using this.translate.use(‘DE’), ensure to use the correct language code as it is case-sensitive and ensure the file name is exact.
Conclusion:
Internationalization is a key element of modern software development, and Angular offers robust tools for creating multilingual applications. With the ngx-translate library, implementing i18n in Angular becomes both simpler and more adaptable.
In this article, we’ve covered how to use ngx-translate to generate translation files, apply translations in templates, and switch languages within an Angular application. By following these guidelines, you can effortlessly build a multilingual app accessible to users worldwide.
Thank you!
Feel free to leave comments if you have any questions
Top comments (0)