Translate Angular 8 App Using ngx-translate

Introduction

 
In this article, we are going to see how to translate by applying different languages in our application using npm package called ngx-tanslate. Ngx Translate provides a feature to translate from one langulage to another.
 

What is ngx-translate ?

 
NGX-Translate is an internationalization library for Angular. It lets you translate for your content in different languages and switch between them easily.
 
Prerequisites
  • Basic knowledge of Angular
  • Visual Studio Code must be installed
  • Angular CLI must be installed
  • Node JS must be installed
Step 1
 
Create a new Angular project using the following NPM command:
  1. ng new ngx-translate
Step 2
 
Now let's add the ngx-translate NPM packages. run the following command
  1. npm install @ngx-translate/core --save  
Also install  ngx-translate-multi-http-loader using the following command
  1. npm i ngx-translate-multi-http-loader  
Step 3
 
Create a new Home Component using the following NPM command,
  1. ng g c home
Step 4
 
Give Home component selector in app.component.html
  1. <app-home></app-home>  
Step 5 
 
After then let's inmport our installed ngx-translate inside app.module.ts file
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { AppComponent } from './app.component';  
  5. import { HttpClientModule, HttpClient } from '@angular/common/http';  
  6.   
  7. import { TranslateModule, TranslateLoader } from '@ngx-translate/core';  
  8. import { MultiTranslateHttpLoader } from "ngx-translate-multi-http-loader";  
  9. import { HomeComponent } from './home/home.component';  
  10.   
  11. // AoT requires an exported function for factories  
  12. export function HttpLoaderFactory(http: HttpClient) {  
  13.   return new MultiTranslateHttpLoader(http, [  
  14.     { prefix: "./assets/translate/menu/", suffix: ".json" },  
  15.   ]);  
  16. }  
  17.   
  18. @NgModule({  
  19.   declarations: [  
  20.     AppComponent,  
  21.     HomeComponent  
  22.   ],  
  23.   imports: [  
  24.     BrowserModule,  
  25.     FormsModule,  
  26.     HttpClientModule,  
  27.     TranslateModule.forRoot({  
  28.       loader: {  
  29.         provide: TranslateLoader,  
  30.         useFactory: HttpLoaderFactory,  
  31.         deps: [HttpClient]  
  32.       }  
  33.     })  
  34.   ],  
  35.   providers: [],  
  36.   bootstrap: [AppComponent]  
  37. })  
  38. export class AppModule { }  
Step 6  
 
In this step I am creating a navbar and a selection box where some languages are there. 
 
Open home component.html file and paste inside the below code.
 
home.component.html 
  1. <nav class="navbar navbar-expand-lg navbar-light bg-light">    
  2.   <a class="navbar-brand" href="#">Ngx-Translate Example</a>    
  3.   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"    
  4.     aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">    
  5.     <span class="navbar-toggler-icon"></span>    
  6.   </button>    
  7.     
  8.   <div class="collapse navbar-collapse" id="navbarSupportedContent">    
  9.     <ul class="navbar-nav mr-auto">    
  10.       <li class="nav-item active">    
  11.         <a class="nav-link">{{'Home' | translate}}</a>    
  12.       </li>    
  13.       <li class="nav-item">    
  14.         <a class="nav-link">{{'About Us' | translate}}</a>    
  15.       </li>    
  16.       <li class="nav-item">    
  17.         <a class="nav-link">{{'Contact Us' | translate}}</a>    
  18.       </li>    
  19.     </ul>    
  20.     <form class="form-inline my-2 my-lg-0">    
  21.       <select class="language-select" name="langChange" (ngModelChange)="languageChange($event)"    
  22.         [(ngModel)]="languageCode">    
  23.     
  24.         <option class="language-select" *ngFor='let item of languages' [ngValue]='item.languageCode'>    
  25.           {{item.languageName}}</option>    
  26.       </select>    
  27.     </form>    
  28.   </div>    
  29. </nav>    
  30. <div style="text-align: center;">    
  31.   <p>    
  32.     {{'How to translate your application' | translate}}    
  33.     {{'The JSON translation file' | translate}}    
  34.     
  35.     {{'Each language is stored in a separate .json file. Lets create the JSON file for the English translation:assets/i18n/en.json' | translate}}    
  36.     
  37.     
  38.   </p>    
  39.   <p>    
  40.     {{'Switching languages at runtime' | translate}}    
  41.     {{'To switch language you will first have to add a new JSON file for that language. Lets create a German translation for the demo: assets/i18n/de.json' | translate}}    
  42.   </p>    
  43. </div>     
We are using translate pipe to translate it into the selected language.
Step 7
 
Now in home.component.ts file just paste the below code.
 
home.component.ts 
  1. import { Component, OnInit } from '@angular/core';  
  2. import { TranslateService } from '@ngx-translate/core';  
  3.   
  4. @Component({  
  5.   selector: 'app-home',  
  6.   templateUrl: './home.component.html',  
  7.   styleUrls: ['./home.component.css']  
  8. })  
  9. export class HomeComponent implements OnInit {  
  10.   currentLanguage: any = 'en';  
  11.   languageCode = 'en';  
  12.   constructor(public translate: TranslateService,) { }  
  13.   languages = [  
  14.     { 'languageCode''en''languageName''English' },  
  15.     { 'languageCode''hi''languageName''Hindi' },  
  16.     { 'languageCode''ar''languageName''Arabic' }  
  17.   ]  
  18.   ngOnInit() {  
  19.   }  
  20.   languageChange($event) {  
  21.     debugger;  
  22.     this.currentLanguage = $event;  
  23.     this.translate.use(this.currentLanguage);  
  24.   }  
  25.   
  26. }  
In this example I am using 3 languages which are English, Hindi,  and Arabic. (English is my defaulted language.) You can use as many languages as you want. 
 
 
In home.component.ts file we need to import a translate service from @ngx-translate/core package inject the service in constructor and use it after changing the language.
 
Step 8
 
Now create a folder inside assets, name it 'translate,' inside of it create a json file. For example if we want to store content for the Hindi language we can create a json file hi.json inside it and  paste the below code.
 
Each language is stored in a separate .json file.  
 
To switch languages you will first have to add a new JSON file for that language. Let's create a Hindi translation for the demo: assets/Translate/hi.json.
hi.json 
  1. {  
  2.     "Home""घर",  
  3.     "About Us""हमारे बारे में",  
  4.     "Contact Us""संपर्क करें",  
  5.     "How to translate your application""अपने आवेदन का अनुवाद कैसे करें",  
  6.     "The JSON translation file""JSON अनुवाद फ़ाइल",  
  7.     "Each language is stored in a separate .json file. Lets create the JSON file for the English translation:assets/i18n/en.json""प्रत्येक भाषा को एक अलग .json फ़ाइल में संग्रहीत किया जाता है। अंग्रेजी अनुवाद के लिए JSON फ़ाइल बनाएँ:संपत्ति / i18n / en.json",  
  8.     "Switching languages at runtime""रनटाइम पर भाषाओं को स्विच करना",  
  9.     "To switch language you will first have to add a new JSON file for that language. Lets create a German translation for the demo: assets/i18n/de.json""भाषा स्विच करने के लिए आपको सबसे पहले उस भाषा के लिए एक नई JSON फाइल जोड़ना होगा। के लिए एक जर्मन अनुवाद बनाते हैं डेमो: संपत्ति / i18n / de.json"  
  10. }  
For Arabic language:
 
ar.json 
  1. {  
  2.     "Home""الصفحة الرئيسية",  
  3.     "About Us""معلومات عنا",  
  4.     "Contact Us""اتصل بنا",  
  5.     "How to translate your application""كيفية ترجمة طلبك",  
  6.     "The JSON translation file""ملف ترجمة JSON",  
  7.     "Each language is stored in a separate .json file. Lets create the JSON file for the English translation:assets/i18n/en.json""يتم تخزين كل لغة في ملف json منفصل. يتيح إنشاء ملف JSON للترجمة الإنجليزية: asset / i18n / en.json",  
  8.     "Switching languages at runtime""تبديل اللغات في وقت التشغيل",  
  9.     "To switch language you will first have to add a new JSON file for that language. Lets create a German translation for the demo: assets/i18n/de.json""لتبديل اللغة ، يجب عليك أولاً إضافة ملف JSON جديد لتلك اللغة. يتيح إنشاء ترجمة ألمانية للعرض التوضيحي: asset / i18n / de.json"  
  10. }  
Now it's time to see the output:
 
Example of Ngx-Translate Translating in Hindi language:
 
Example of Ngx-Translate Translating in Arabic language:
 

Conclusion

 
In this article we have seen how to change languages in Angular using ngx-translate and also switched language from English to Hindi and Arabic. 
 
I hope you have enjoyed this article as much as I have enjoyed writing and coding the examples.
 
Please let me know in the comments how I could improve it and any suggestions from your end.


Similar Articles