Angular Content Localization Using ngx-translate

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, the internalization is like a process of designing an application in which the application will have the portability of supporting 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 on 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 the 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
 
And 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 which 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 which support English and Spanish for 10 country names in both languages. For your kind reference please refer below. Create a JSON file named as en.json and place the following code inside of it.
 
English-en.json
  1. {  
  2.     "lbl-country-name1""Iceland",  
  3.     "lbl-country-name2""Kyrgyzstan",  
  4.     "lbl-country-name3""New Zealand",  
  5.     "lbl-country-name4""North Korea",  
  6.     "lbl-country-name5""Philippines",  
  7.     "lbl-country-name6""Saudi Arabia",  
  8.     "lbl-country-name7""Solomon Islands",  
  9.     "lbl-country-name8""Suazilandia",  
  10.     "lbl-country-name9""United Arab Emirates",  
  11.     "lbl-country-name10""United States of Americ"  
  12. }  
And now create another json file in the same asset folder and name it as es-json and place the following code inside of it. 
 
Spanish-es.json
  1. {  
  2.     "lbl-country-name1""Islandia",  
  3.     "lbl-country-name2""Kirguistán",  
  4.     "lbl-country-name3""Nueva Zelanda",  
  5.     "lbl-country-name4""Corea del Norte",  
  6.     "lbl-country-name5""Filipinas",  
  7.     "lbl-country-name6""Arabia Saudita",  
  8.     "lbl-country-name7""Islas Salomón",  
  9.     "lbl-country-name8""Swaziland",  
  10.     "lbl-country-name9""Emiratos Árabes Unidos",  
  11.     "lbl-country-name10""Estados Unidos"  
  12. }  
And the important point is not to forget importing the ngx-translate libraries into app.module.ts
 
Open app.module.ts file and replace the following as mentioned below.
  1. import {  
  2.     TranslateModule,  
  3.     TranslateLoader,  
  4.     TranslateService  
  5. } from '@ngx-translate/core';  
  6. import {  
  7.     TranslateHttpLoader  
  8. } from '@ngx-translate/http-loader';  
  9. import {  
  10.     LanguageTranslationModule  
  11. } from './services/language-translation.module';  
  12. export function HttpLoaderFactory(https: HttpClient) {  
  13.     return new TranslateHttpLoader(https, './assets/i18n/''.json');  
  14. }  
  15. @NgModule({  
  16.     imports: [  
  17.         LanguageTranslationModule,  
  18.         TranslateModule.forRoot({  
  19.             loader: {  
  20.                 provide: TranslateLoader,  
  21.                 useFactory: HttpLoaderFactory,  
  22.                 deps: [HttpClient]  
  23.             }  
  24.         })  
  25.     ],  
  26.     declarations: [  
  27.         AppComponent,  
  28.     ],  
  29.     providers: [TranslateService],  
  30.     bootstrap: [AppComponent],  
  31. })  
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 app.module.ts file and add the following code inside of it.
  1. import {  
  2.     NgModule  
  3. } from '@angular/core';  
  4. import {  
  5.     HttpClient  
  6. } from '@angular/common/http';  
  7. // import ngx-translate and the http loader  
  8. import {  
  9.     TranslateLoader,  
  10.     TranslateModule,  
  11.     TranslateService  
  12. } from '@ngx-translate/core';  
  13. import {  
  14.     TranslateHttpLoader  
  15. } from '@ngx-translate/http-loader';  
  16. import {  
  17.     CookieService  
  18. } from 'ngx-cookie-service';  
  19. // ngx-translate - required for AOT compilation  
  20. export function HttpLoaderFactory(http: HttpClient) {  
  21.     return new TranslateHttpLoader(http);  
  22. }  
  23. @NgModule({  
  24.     declarations: [],  
  25.     imports: [  
  26.         TranslateModule.forRoot({  
  27.             loader: {  
  28.                 provide: TranslateLoader,  
  29.                 useFactory: HttpLoaderFactory,  
  30.                 deps: [HttpClient]  
  31.             }  
  32.         })  
  33.     ],  
  34.     exports: [  
  35.         TranslateModule  
  36.     ],  
  37. })  
  38. export class LanguageTranslationModule {  
  39.     constructor(private _cookieService: CookieService, private translate: TranslateService, ) {  
  40.         // Gets Default language from browser if available, otherwise set English ad default  
  41.         var lang = "en";  
  42.         if (this._cookieService.get('languages') != null || this._cookieService.get('languages') != undefined) {  
  43.             if (this._cookieService.get('languages') == 'es') {  
  44.                 lang = "es";  
  45.             }  
  46.         }  
  47.         this.translate.addLangs(['en''es']);  
  48.         this.translate.setDefaultLang(lang);  
  49.         // const browserLang = this.translate.getBrowserLang();  
  50.         this.translate.use(lang);  
  51.     }  
  52. }  
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 setup ngx-translate for working with AOT and for that open app.component.ts and place the following code inside of it.
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     CookieService  
  7. } from 'ngx-cookie-service';  
  8. import {  
  9.     TranslateService  
  10. } from '@ngx-translate/core';  
  11. @Component({  
  12.     selector: 'app-component',  
  13.     templateUrl: './app.component.html',  
  14.     styleUrls: ['./app.component.css'],  
  15. })  
  16. export class AppComponent implements OnInit {  
  17.     constructor(private _cookieService: CookieService, private translate: TranslateService, ) {}  
  18.     ngOnInit() {}  
  19.     changeLang(language: string) {  
  20.         this.translate.use(language);  
  21.         this._cookieService.set('languages', language, 1000000);  
  22.     }  
  23. }  
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 file 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.
  1. <h6>{{ 'lbl-country-name1' | translate }}</h6>    
Here we are in the last stage of the process, open app.component.html file and replace the following code inside of it.
  1. <h4 class="text-center">Language Selection</h4>  
  2. <div class="row cursorpoint">  
  3.     <div class="col-xs-12 col-lg-6 text-center">  
  4.         <div class="input-effect">  
  5.             <div (click)="changeLang('en')"> {{ 'English' | translate }}</div>  
  6.         </div>  
  7.     </div>  
  8.     <div class="col-xs-12 col-lg-6 text-center">  
  9.         <div class="input-effect">  
  10.             <div (click)="changeLang('es')"> {{ 'Spanish' | translate }}</div>  
  11.         </div>  
  12.     </div>  
  13. </div>  
  14. <div class="text-center">  
  15.     <h6>{{ 'lbl-country-name1' | translate }}</h6>  
  16.     <h6>{{ 'lbl-country-name2' | translate }}</h6>  
  17.     <h6>{{ 'lbl-country-name3' | translate }}</h6>  
  18.     <h6>{{ 'lbl-country-name4' | translate }}</h6>  
  19.     <h6>{{ 'lbl-country-name5' | translate }}</h6>  
  20.     <h6>{{ 'lbl-country-name6' | translate }}</h6>  
  21.     <h6>{{ 'lbl-country-name7' | translate }}</h6>  
  22.     <h6>{{ 'lbl-country-name8' | translate }}</h6>  
  23.     <h6>{{ 'lbl-country-name9' | translate }}</h6>  
  24.     <h6>{{ 'lbl-country-name10' | translate }}</h6>  
  25. </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 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 improve my article word flow. Thanks for reading.