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:
Step 2
Now let's add the ngx-translate NPM packages. run the following command
- npm install @ngx-translate/core --save
Also install ngx-translate-multi-http-loader using the following command
- npm i ngx-translate-multi-http-loader
Step 3
Create a new Home Component using the following NPM command,
Step 4
Give Home component selector in app.component.html
Step 5
After then let's inmport our installed ngx-translate inside app.module.ts file
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { FormsModule } from '@angular/forms';
- import { AppComponent } from './app.component';
- import { HttpClientModule, HttpClient } from '@angular/common/http';
-
- import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
- import { MultiTranslateHttpLoader } from "ngx-translate-multi-http-loader";
- import { HomeComponent } from './home/home.component';
-
-
- export function HttpLoaderFactory(http: HttpClient) {
- return new MultiTranslateHttpLoader(http, [
- { prefix: "./assets/translate/menu/", suffix: ".json" },
- ]);
- }
-
- @NgModule({
- declarations: [
- AppComponent,
- HomeComponent
- ],
- imports: [
- BrowserModule,
- FormsModule,
- HttpClientModule,
- TranslateModule.forRoot({
- loader: {
- provide: TranslateLoader,
- useFactory: HttpLoaderFactory,
- deps: [HttpClient]
- }
- })
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- 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
- <nav class="navbar navbar-expand-lg navbar-light bg-light">
- <a class="navbar-brand" href="#">Ngx-Translate Example</a>
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
- aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
-
- <div class="collapse navbar-collapse" id="navbarSupportedContent">
- <ul class="navbar-nav mr-auto">
- <li class="nav-item active">
- <a class="nav-link">{{'Home' | translate}}</a>
- </li>
- <li class="nav-item">
- <a class="nav-link">{{'About Us' | translate}}</a>
- </li>
- <li class="nav-item">
- <a class="nav-link">{{'Contact Us' | translate}}</a>
- </li>
- </ul>
- <form class="form-inline my-2 my-lg-0">
- <select class="language-select" name="langChange" (ngModelChange)="languageChange($event)"
- [(ngModel)]="languageCode">
-
- <option class="language-select" *ngFor='let item of languages' [ngValue]='item.languageCode'>
- {{item.languageName}}</option>
- </select>
- </form>
- </div>
- </nav>
- <div style="text-align: center;">
- <p>
- {{'How to translate your application' | translate}}
- {{'The JSON translation file' | translate}}
-
- {{'Each language is stored in a separate .json file. Lets create the JSON file for the English translation:assets/i18n/en.json' | translate}}
-
-
- </p>
- <p>
- {{'Switching languages at runtime' | translate}}
- {{'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}}
- </p>
- </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
- import { Component, OnInit } from '@angular/core';
- import { TranslateService } from '@ngx-translate/core';
-
- @Component({
- selector: 'app-home',
- templateUrl: './home.component.html',
- styleUrls: ['./home.component.css']
- })
- export class HomeComponent implements OnInit {
- currentLanguage: any = 'en';
- languageCode = 'en';
- constructor(public translate: TranslateService,) { }
- languages = [
- { 'languageCode': 'en', 'languageName': 'English' },
- { 'languageCode': 'hi', 'languageName': 'Hindi' },
- { 'languageCode': 'ar', 'languageName': 'Arabic' }
- ]
- ngOnInit() {
- }
- languageChange($event) {
- debugger;
- this.currentLanguage = $event;
- this.translate.use(this.currentLanguage);
- }
-
- }
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
- {
- "Home": "घर",
- "About Us": "हमारे बारे में",
- "Contact Us": "संपर्क करें",
- "How to translate your application": "अपने आवेदन का अनुवाद कैसे करें",
- "The JSON translation file": "JSON अनुवाद फ़ाइल",
- "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",
- "Switching languages at runtime": "रनटाइम पर भाषाओं को स्विच करना",
- "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"
- }
For Arabic language:
ar.json
- {
- "Home": "الصفحة الرئيسية",
- "About Us": "معلومات عنا",
- "Contact Us": "اتصل بنا",
- "How to translate your application": "كيفية ترجمة طلبك",
- "The JSON translation file": "ملف ترجمة JSON",
- "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",
- "Switching languages at runtime": "تبديل اللغات في وقت التشغيل",
- "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"
- }
Now it's time to see the output:
Example of Ngx-Translate Translating in Hindi language:
Example of Ngx-Translate Translating in Arabic language:
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.