Internationalization (i18n) enables your application to deal with multiple languages and formats from a specific culture, hence increasing the range of going global. Angular has built in tools for i18n, which enable it to automatically manage translations and adapt content according to the user's locale.
Before getting into the implementation, let's make sure that:
ng new angular-i18n-demo
cd angular-i18n-demo
npm install @ngx-translate/core @ngx-translate/http-loader
Create JSON files for each language you want to support in a assets/i18n folder.
For example:
en.json (English): json
{
"WELCOME": "Welcome",
"DESCRIPTION": "This is a multilingual app."
}
fr.json (French): json
{
"WELCOME": "Bienvenue",
"DESCRIPTION": "Ceci est une application multilingue."
}
Import the required modules in app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } 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) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
bootstrap: [AppComponent]
})
export class AppModule {}
1. Inject the TranslateService in the AppComponent:
import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-root',
template: `
<div>
<h1>{{ 'WELCOME' | translate }}</h1>
<p>{{ 'DESCRIPTION' | translate }}</p>
<button (click)="switchLanguage('en')">English</button>
<button (click)="switchLanguage('fr')">French</button>
</div>
`,
})
export class AppComponent {
constructor(private translate: TranslateService) {
this.translate.setDefaultLang('en'); // Default language
}
switchLanguage(lang: string) {
this.translate.use(lang);
}
}
2. Add a simple HTML template to display translations and switch between languages.
To run an application, execute the following command in the terminal:
ng serve
Open the app in your browser. You should see content in English by default. Use the buttons to switch between English and French.
const browserLang = this.translate.getBrowserLang();
this.translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
With the implementation of i18n with Angular and ngx-translate, making your app or application globally reachable is easily done. The steps outlined above give a solid ground for effective translation management and the flexibility of ngx-translate means that you scale well as your app expands.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
0