Angular 2/4 NGX Translate Complete Implementation with Example

Angular 2/4 Application Internationalisation/Localisation (i18n) Example using Angular CLI

Step-1: Angular CLI Installation
npm install -g @angular/cli
Generating an Angular project via a development server
ng new angular2-ngx-translate-demo-angular-cli
Serving an Angular project via a development server
ng serve

Navigate to http://localhost:4200/

Create language JSON with the json values to convert to the values. Let's say we are suing English(en) and French(fr) languages for Angular 2 localization.

angular2-ngx-translate-demo-angular-cli/src/i18n/en.json
angular2-ngx-translate-demo-angular-cli/src/i18n/fr.json

The sample content for any language file can be as per below structure:


{
 "header": {
  "title": "Welcome to Angular 4",
  "head": "Here are some links to help you start",
  "list":"Tour of Heroes",
 }
}
and now convert the languages to the next JSON as fr.json:

{
 "header": {
  "title": "Bienvenue chez Angular 4",
  "head": "Voici quelques liens pour vous aider à démarrer",
  "list":"Tour of Heroes",
 }
}

Since the folder structure i18n has been added externally after running the Angular CLI command so we need to update the file:

angular2-ngx-translate-demo-angular-cli/.angular-cli.json

add the i18n into the given json:

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        "i18n"
      ],

Now here we need to add external dependencies of NGX Translate so it is required to install the dependencies using npm

To resolve these dependencies navigate to the project root directory and run the following command:

npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save

Now its time to configure ngx translate services with our project. So let's open the file:

angular2-ngx-translate-demo-angular-cli/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {TranslateModule, TranslateLoader} from "@ngx-translate/core";
import {TranslateHttpLoader} from "@ngx-translate/http-loader";
import {HttpModule , Http} from "@angular/http";

import { AppComponent } from './app.component';

export function HttpLoaderFactory(http: Http) {
    return new TranslateHttpLoader(http, "i18n/", ".json");
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    TranslateModule.forRoot({   
        loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [Http]
        }
      })    
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Once ngx translate services has been configured using main module typescript file so let's use the ngx translate service on component.

Open the component typescript file angular2-ngx-translate-demo-angular-cli/src/app/app.component.ts and import the dependency

import { Component } from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  
  constructor(private translate: TranslateService) {
    translate.addLangs(["en", "hi"]);
       translate.setDefaultLang('en');

       let browserLang = translate.getBrowserLang();
       translate.use(browserLang.match(/en|hi/) ? browserLang : 'en');
   }
}

Now it's the final step to open the template file angular2-ngx-translate-demo-angular-cli/src/app/app.component.html. Here we want the select component to switch between the languages and we have used the double curly brackets to read and render the static text values based on the drop down language selection.

<div style="padding-top:15px;padding-right:5px;">

<label><span style="color:white">{{ 'header.select' | translate }}</span>
     <select #langSelect (change)="translate.use(langSelect.value)">
          <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}
          </option>
     </select>
</label>
</div>

<!--The whole content below can be removed with the new code.-->
<div style="text-align:center">
  <h1>
    {{ 'header.title' | translate }} {{title}}!!
  </h1>
  <img width="300" src="logo.png"/>
</div>
<h2>{{ 'header.head' | translate }}: </h2>
<ul>
  <li>
    <h2><a target="_blank" href="https://angular.io/tutorial">{{ 'header.list1' | translate }}</a></h2>
  </li>
  <li>
    <h2><a target="_blank" href="https://github.com/angular/angular-cli/wiki">{{ 'header.list2' | translate }}</a></h2>
  </li>
  <li>
    <h2><a target="_blank" href="http://angularjs.blogspot.ca/">{{ 'header.list3' | translate }}</a></h2>
  </li>
</ul>

Comments

Popular posts from this blog

Angular 2/4 Content Translation using ngx-translate

Angular 2/4 and TypeScript Dynamically Access/Append HTML Nodes