Angular 2, AngularJS

Angular 2 with i18n

In some applications it is necessary to provide multilingual support to offer users the possibility to view your application in different languages. So to provide this facility we can build our application using i18n feature in Angular. Here we are going to build simple application to translate “Hello World” into different languages(Eg: English, French, German).

What is i18n ?

Internationalization is the design and development of a product, application or document content that enables easy localization for target audiences that vary in culture, region, or language.

Let’s start with the example of i18n with Angular 2 using ng2-translate.

Installation :

First you need to install the npm module:

npm install ng2-translate

Usage :

  • Import the TranslateModule:
    It is recommended to import TranslateModule.forRoot() in the NgModule of your application. For now ng2-translate requires HttpModule from @angular/http. By convention, the forRoot static method both provides and configures services at the same time.This method allows you to configure the TranslateModule loader. By default it will use the TranslateStaticLoader (you can use another loader as well).
    The TranslateStaticLoader builder creates a loading function for a typical static file url pattern: “lang-en_US.json“, “lang-de_DE.json“, etc.
    It will search for files in i18n/*.json.

     // file : app.module.ts
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule, Http } from '@angular/http';
    import { TranslateModule, TranslateLoader, TranslateStaticLoader } from "ng2-translate/ng2-translate";
    
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        TranslateModule.forRoot({
          provide: TranslateLoader,
          useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
          deps: [Http]
        }),
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
  • Init the TranslateService:
     //file : app.component.ts
    import { Component } from '@angular/core';
    import {TranslateService} from 'ng2-translate';
    
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      
      // define supported languages for application
      public LANGUAGES: any[] = ["en", "fr", "de"];
    
      constructor(private translate: TranslateService) {
          translate.addLangs(this.LANGUAGES);
          let browserLang = translate.getBrowserLang();
          let joinLangs = this.LANGUAGES.join("|");
    
          translate.use(browserLang.match(/joinLangs/) ? browserLang : 'en');
      }
    
    }
  • Create application template:
    Here we are displaying select box with available languages using ngFor. On language selection it shows the translated text accordingly. We have used the translate pipe to get translations. (we can use service or directive as well to get translations)component.png
  • Define the translations:
    We need to add translations in a json file which will be imported using TranslateStaticLoader. The structure of .json file should be like this:

     // file : assets/i18n/en.json
    // contains translation for English
    {
      "HOME": {
        "TITLE": "Hello World !!!",
        "SELECT": "Change Language"
      }
    }
    
    // file : assets/i18n/fr.json
    // contains translation for French
    {
      "HOME": {
        "TITLE": "Bonjour le monde !!!",
        "SELECT": "Changer la langue"
      }
    }
    
    // file : assets/i18n/de.json
    // contains translation for German
    {
      "HOME": {
        "TITLE": "Hallo Welt",
        "SELECT": "Ändern Sie die Sprache"
      }
    }

    Once we are done with this our application is now ready. The final UI looks like this:
    eng-lang.png
    If we change another language , then it looks like as below – french-lang.png

Download sample code from zCon Solutions Github Repo


Written by Dipali Shinde, Sr. Software Engg. at zCon Solutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s