Welcome everyone! It’s been a few days since I wrote my last article and it feels good to be back again. In this article let’s explore implementing the internationalization and localization in Angular 8. Before getting into implementation, let’s take an intro about what is internalization and localization in Angular.
Internationalization (i18n) and localization
Basically, internalization is like a process of designing an application in which the application will have the portability to support multiple languages with the required supporting files. As for localization, it's a process of translating the language from one to another. We can also describe it in this way too; it means localization will take the place of translating the required language of the user's needs.
Let’s get back to internalization and have an overview about why the internalization is so important. Consider when we are building a software application, of course, a team will be involved in developing it. First, we will take an overview on building an infrastructure based on a particular language, and then the app will be supported by numerous different demographics so, for that, we have to do the internalization process in which the application will support multiple languages.
In addition to that, we can use the third-party library functions for the internationalization.
In our Angular application, we just need to use ngx-translate, it’s one of the most popular libraries for internalization. The mentioned library function can be also used in both JIT and AOT compiler versions of the Angular application. The ngx-translate library is been supported by Angular 2+.
Prerequisites
- Angular CLI
- Visual Studio Code IDE
Setting-up
Step 1. First of all, let’s create a new Angular application by using the following command since Angular 9 has come along. Let's update the Angular CLI from the Angular previous version to Angular 9. Use the following command to update the Angular CLI.
npm install -g @angular/cli
Use the following command to check whether the CLI has been updated to CLI 9.
ng v
Now create a new Angular application by using the following command.
ng new AngularTranslator
Step 2. Open the project in the Visual Studio Code IDE and let’s create a JSON file that contains a collection of different languages including English, Spanish, German, etc. Create the JSON file in the asset folder /assets/i18n/folder. In the following project, I have created two JSON collection files that support English and Spanish for 10 country names in both languages. For your kind reference please refer below. Create a JSON file named en.json and place the following code inside of it.
English-en.json
{
"lbl-country-name1": "Iceland",
"lbl-country-name2": "Kyrgyzstan",
"lbl-country-name3": "New Zealand",
"lbl-country-name4": "North Korea",
"lbl-country-name5": "Philippines",
"lbl-country-name6": "Saudi Arabia",
"lbl-country-name7": "Solomon Islands",
"lbl-country-name8": "Suazilandia",
"lbl-country-name9": "United Arab Emirates",
"lbl-country-name10": "United States of America"
}
Now create another JSON file in the same asset folder name it as es-json and place the following code inside of it.
Spanish-es.json
{
"lbl-country-name1": "Islandia",
"lbl-country-name2": "Kirguistán",
"lbl-country-name3": "Nueva Zelanda",
"lbl-country-name4": "Corea del Norte",
"lbl-country-name5": "Filipinas",
"lbl-country-name6": "Arabia Saudita",
"lbl-country-name7": "Islas Salomón",
"lbl-country-name8": "Swaziland",
"lbl-country-name9": "Emiratos Árabes Unidos",
"lbl-country-name10": "Estados Unidos"
}
The important point is not to forget to import the ngx-translate libraries into app.module.ts.
Open the app.module.ts file and replace the following as mentioned below.
import {
TranslateModule,
TranslateLoader,
TranslateService
} from '@ngx-translate/core';
import {
TranslateHttpLoader
} from '@ngx-translate/http-loader';
import {
LanguageTranslationModule
} from './services/language-translation.module';
export function HttpLoaderFactory(https: HttpClient) {
return new TranslateHttpLoader(https, './assets/i18n/', '.json');
}
@NgModule({
imports: [
LanguageTranslationModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
declarations: [
AppComponent,
],
providers: [TranslateService],
bootstrap: [AppComponent],
})
Step 3. Now let’s configure the TranslateModule for loading the assets. Switch to the directory of assets/i18n/.json files and then we can initialize the LanguageTranslationModule. The main point is we have to set the default language. Open the app.module.ts file and add the following code inside of it.
import {
NgModule
} from '@angular/core';
import {
HttpClient
} from '@angular/common/http';
// import ngx-translate and the http loader
import {
TranslateLoader,
TranslateModule,
TranslateService
} from '@ngx-translate/core';
import {
TranslateHttpLoader
} from '@ngx-translate/http-loader';
import {
CookieService
} from 'ngx-cookie-service';
// ngx-translate - required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [],
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
exports: [
TranslateModule
],
})
export class LanguageTranslationModule {
constructor(private _cookieService: CookieService, private translate: TranslateService) {
// Gets Default language from browser if available, otherwise set English as default
let lang = "en";
if (this._cookieService.get('languages') !== null && this._cookieService.get('languages') !== undefined) {
if (this._cookieService.get('languages') === 'es') {
lang = "es";
}
}
this.translate.addLangs(['en', 'es']);
this.translate.setDefaultLang(lang);
// const browserLang = this.translate.getBrowserLang();
this.translate.use(lang);
}
}
We can see that we have used the CookieService to set the default language, thus it will be stored in the cookie and there is one more step to proceed. We can also set up ngx-translate for working with AOT and for that open app.component.ts and place the following code inside of it.
import {
Component,
OnInit
} from '@angular/core';
import {
CookieService
} from 'ngx-cookie-service';
import {
TranslateService
} from '@ngx-translate/core';
@Component({
selector: 'app-component',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
constructor(private _cookieService: CookieService, private translate: TranslateService) {}
ngOnInit() {}
changeLang(language: string) {
this.translate.use(language);
this._cookieService.set('languages', language, 1000000);
}
}
In addition to that we can use TranslationService if we need to localize the content in the component page. ChangeLang function is used to store the language and change the language in JSON files like en.json to es.json.
It means the language will be changed from English to Spanish at the language switching and it is stored in cookies.
We can also use TranslatePipe in HTML files for translating the content, we can use TranslatePipe like the following.
<h6>{{ 'lbl-country-name1' | translate }}</h6>
Here we are in the last stage of the process, open the app.component.html file and replace the following code inside of it.
<h4 class="text-center">Language Selection</h4>
<div class="row cursorpoint">
<div class="col-xs-12 col-lg-6 text-center">
<div class="input-effect">
<div (click)="changeLang('en')">{{ 'English' | translate }}</div>
</div>
</div>
<div class="col-xs-12 col-lg-6 text-center">
<div class="input-effect">
<div (click)="changeLang('es')">{{ 'Spanish' | translate }}</div>
</div>
</div>
</div>
<div class="text-center">
<h6>{{ 'lbl-country-name1' | translate }}</h6>
<h6>{{ 'lbl-country-name2' | translate }}</h6>
<h6>{{ 'lbl-country-name3' | translate }}</h6>
<h6>{{ 'lbl-country-name4' | translate }}</h6>
<h6>{{ 'lbl-country-name5' | translate }}</h6>
<h6>{{ 'lbl-country-name6' | translate }}</h6>
<h6>{{ 'lbl-country-name7' | translate }}</h6>
<h6>{{ 'lbl-country-name8' | translate }}</h6>
<h6>{{ 'lbl-country-name9' | translate }}</h6>
<h6>{{ 'lbl-country-name10' | translate }}</h6>
</div>
Now it’s time to wrap all the things up. Yay! We can run our Angular application now and we can see the following output. Use the following code for compiling the application and view the output in the browser.
ng serve --open
I hope this article will be useful for you and do comment below if you have any queries so that I can share my knowledge with you and improve my article's word flow. Thanks for reading.