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. import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
  7. import { MultiTranslateHttpLoader } from "ngx-translate-multi-http-loader";
  8. import { HomeComponent } from './home/home.component';
  9. // AoT requires an exported function for factories
  10. export function HttpLoaderFactory(http: HttpClient) {
  11. return new MultiTranslateHttpLoader(http, [
  12. { prefix: "./assets/translate/menu/", suffix: ".json" },
  13. ]);
  14. }
  15. @NgModule({
  16. declarations: [
  17. AppComponent,
  18. HomeComponent
  19. ],
  20. imports: [
  21. BrowserModule,
  22. FormsModule,
  23. HttpClientModule,
  24. TranslateModule.forRoot({
  25. loader: {
  26. provide: TranslateLoader,
  27. useFactory: HttpLoaderFactory,
  28. deps: [HttpClient]
  29. }
  30. })
  31. ],
  32. providers: [],
  33. bootstrap: [AppComponent]
  34. })
  35. 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. <div class="collapse navbar-collapse" id="navbarSupportedContent">
  8. <ul class="navbar-nav mr-auto">
  9. <li class="nav-item active">
  10. <a class="nav-link">{{'Home' | translate}}</a>
  11. </li>
  12. <li class="nav-item">
  13. <a class="nav-link">{{'About Us' | translate}}</a>
  14. </li>
  15. <li class="nav-item">
  16. <a class="nav-link">{{'Contact Us' | translate}}</a>
  17. </li>
  18. </ul>
  19. <form class="form-inline my-2 my-lg-0">
  20. <select class="language-select" name="langChange" (ngModelChange)="languageChange($event)"
  21. [(ngModel)]="languageCode">
  22. <option class="language-select" *ngFor='let item of languages' [ngValue]='item.languageCode'>
  23. {{item.languageName}}</option>
  24. </select>
  25. </form>
  26. </div>
  27. </nav>
  28. <div style="text-align: center;">
  29. <p>
  30. {{'How to translate your application' | translate}}
  31. {{'The JSON translation file' | translate}}
  32. {{'Each language is stored in a separate .json file. Lets create the JSON file for the English translation:assets/i18n/en.json' | translate}}
  33. </p>
  34. <p>
  35. {{'Switching languages at runtime' | translate}}
  36. {{'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}}
  37. </p>
  38. </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. @Component({
  4. selector: 'app-home',
  5. templateUrl: './home.component.html',
  6. styleUrls: ['./home.component.css']
  7. })
  8. export class HomeComponent implements OnInit {
  9. currentLanguage: any = 'en';
  10. languageCode = 'en';
  11. constructor(public translate: TranslateService,) { }
  12. languages = [
  13. { 'languageCode': 'en', 'languageName': 'English' },
  14. { 'languageCode': 'hi', 'languageName': 'Hindi' },
  15. { 'languageCode': 'ar', 'languageName': 'Arabic' }
  16. ]
  17. ngOnInit() {
  18. }
  19. languageChange($event) {
  20. debugger;
  21. this.currentLanguage = $event;
  22. this.translate.use(this.currentLanguage);
  23. }
  24. }
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.