English is not the first language for a sizable population of the world; therefore building an app that just renders in English may not be a very wise idea. Imagine, with just some content localization, how much we can gain in terms of application reach. Internationalization is all about designing our app so that anyone in any region of the world can use the app in their native locale. Before we dive deeper into this topic, why not address a common confusion between what internationalization (I18n) and what localization (L10n) is.
Internationalization (I18n) is the process of making sure that the application has elements that can help it render locale-specific content. In other words, the application is adaptable to different locales. Localization (L10n) on the other hand, is the actual process of adapting parts of the application to specific locales. These could be the text shown, the date, the time, the current formatting, and other such content that is affected by locale change.
It is a normal tendency to just overlook this topic and believe that the app we are building does not need to handle I18n concerns. But even apps targeted at an English language audience need to manage locale variations that are country-specific. We may be able to work with the text content, but we still need to handle date, number, and currency variations.
For example, en-us (language code, English: United States) and en-gb (English: United Kingdom) have variations. The US date format is MM/DD/YY whereas for the UK, it is DD/MM/YY. The same holds true for currency formatting too.
What is the purpose of i18n?
Internationalization (or i18n, which stands for i--n) is the process of adapting software and web applications to multiple languages, allowing their application to be used by multiple language-speaking users. By ensuring that your application supports multiple languages, you can reach a broader audience and ensure a smooth user experience for multilingual users.
Process & Roles
In order for an application to successfully support multiple languages, multiple team members must closely dedicate their efforts to working together. Translators must be introduced to the team as they will be the ones translating the content and will need guidance on the intent and meaning of the words being used. Using Angular's i18n facilities, the process would look like this.
- Mark text messages in your templates for translation.
- Use an Angular i18n tool to extract the messages into an industry standard translation source file.
- Provide the industry standard translation source files to a translator, who will translate the files and give them back to you.
- Import the completed translation files using the Angular compiler.
Unlike Angular 1.x, Angular 2.0 does not have its own readymade localization. But, we can achieve the goal by creating the translation service.
For doing this, create the below files as mentioned.
English.ts (This file is used basically as dictionary for the English language)
- export const LANG_EN_NAME = 'en';
- export const LANG_EN_CURRENCY = 'INR';
- export const LANG_EN_DATEFORMAT = 'mm/dd/yyyy';
- export const LANG_EN_TRANS = {
- "HEADLINE": 'Hello there, This is my awesome app!',
- "INTRO_TEXT": 'And it has i18n support!',
- "BUTTON_TEXT_EN": 'english',
- "BUTTON_TEXT_DE": 'german'
- }
German.ts (This file is used basically as dictionary for the German language)
- export const LANG_EN_DE_NAME = 'de';
- export const LANG_EN_DE_CURRENCY = 'DEM';
- export const LANG_EN_DE_DATEFORMAT = 'dd/mm/yyyy';
- export const LANG_EN_DE_TRANS = {
- "HEADLINE": 'Hey, das ist meine großartige App!',
- "INTRO_TEXT": 'Und sie untersützt mehrere Sprachen!',
- "BUTTON_TEXT_EN": 'englisch',
- "BUTTON_TEXT_DE": 'deutsch'
- }
translatepipe.ts (This file is used basically for transalate any key at HTML part)
- import { Pipe, PipeTransform } from '@angular/core';
- import { TranslateService } from './translateservice.js';
-
- @Pipe({
- name: 'translate',
- pure: false
- })
-
- export class TranslatePipe implements PipeTransform {
-
- constructor(private _translate: TranslateService) { }
-
- transform(value: string, args: any[]): any {
- if (!value) return;
- return this._translate.instant(value);
- }
- }
translateservice.ts (This service file is used to load or save the language key)
- import { Injectable, Inject } from '@angular/core';
- import { Translation, CurrencySymbol, DateFormat } from './translations.js';
-
- @Injectable()
- export class TranslateService {
- currentLang: string = 'en';
-
- constructor( @Inject(Translation) private _translations: any, @Inject(CurrencySymbol) private _currency: any,
- @Inject(DateFormat) private _dateFormat: any) {
- }
-
- public setLocale(key: string): void {
- this.currentLang = key;
- }
-
- public getLocale(): string {
- return this.currentLang;
- }
-
- private translate(key: string): string {
- let translation = key;
- if (this._translations[this.currentLang] && this._translations[this.currentLang][key]) {
- translation = this._translations[this.currentLang][key];
- }
- return translation;
- }
-
- public instant(key: string) {
- return this.translate(key);
- }
-
- public getLocaleCurrency(): string {
- let currency = 'USD';
- if (this._currency[this.currentLang]) {
- return this._currency[this.currentLang];
- }
- return currency;
- }
-
- public getLocaleDateFormat(): string {
- let currency = 'mm/dd/yyyy';
- if (this._dateFormat[this.currentLang]) {
- return this._dateFormat[this.currentLang];
- }
- return currency;
- }
- }
translations.ts (This file is used as constant file to load different language translation providers)
- import { OpaqueToken } from '@angular/core';
- import { LANG_EN_NAME, LANG_EN_TRANS, LANG_EN_CURRENCY, LANG_EN_DATEFORMAT } from './english.js';
- import { LANG_EN_DE_NAME, LANG_EN_DE_TRANS, LANG_EN_DE_CURRENCY, LANG_EN_DE_DATEFORMAT } from './german.js';
-
- export const Translation = new OpaqueToken('translations');
- export const CurrencySymbol = new OpaqueToken('translations');
- export const DateFormat = new OpaqueToken('translations');
-
- const languageDictionary = {
- [LANG_EN_NAME]: LANG_EN_TRANS,
- [LANG_EN_DE_NAME]: LANG_EN_DE_TRANS
- };
-
- const currencyDictionary = {
- [LANG_EN_NAME]: LANG_EN_CURRENCY,
- [LANG_EN_DE_NAME]: LANG_EN_DE_CURRENCY
- }
-
- const dateformatDictionary = {
- [LANG_EN_NAME]: LANG_EN_DATEFORMAT,
- [LANG_EN_DE_NAME]: LANG_EN_DE_DATEFORMAT
- }
-
- export const TRANSLATION_PROVIDERS = [
- { provide: Translation, useValue: languageDictionary },
- { provide: CurrencySymbol, useValue: currencyDictionary },
- { provide: DateFormat, useValue: dateformatDictionary },
- ];
app.component.homepage.html
- <div>
- <h1>Localization</h1>
- <div>
- <button (click)="changeLanguage('en')">English</button>
- <button (click)="changeLanguage('de')">German</button>
- </div>
- <div>
- <h2>{{ 'HEADLINE' | translate }}</h2>
- <p>{{ 'INTRO_TEXT' | translate }}</p>
- </div>
- <div>
- Number : {{106.89 | number:'2.2-2'}}
- <br />
- Currency : {{1123.00 | currency}}
- <br />
- Today's Date :- {{_todayDate | date : "fullDate"}} (Full Date)<br />
- {{_todayDate | date : "longDate"}} (Long Date)<br />
- {{_todayDate | date : "shortDate"}} (Short Date)<br />
- </div>
- </div>
app.component.homepage.ts
- import { Component, OnInit, ViewChild } from '@angular/core';
- import { Http, Response } from '@angular/http';
- import { TranslateService } from '../locale/translateservice.js';
-
- @Component({
- moduleId: module.id,
- selector: 'home-page',
- templateUrl: 'app.component.homepage.html'
- })
-
- export class HomePageComponent implements OnInit {
-
- private _todayDate: Date;
-
- constructor(private _transService: TranslateService) {
- }
-
- ngOnInit(): void {
- this._todayDate = new Date();
- }
-
- changeLanguage(locale: string): void {
- debugger;
- this._transService.setLocale(locale);
-
- }
- }
app.module.ts
- import { NgModule, NO_ERRORS_SCHEMA, LOCALE_ID } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { ReactiveFormsModule } from "@angular/forms";
-
- import { TranslateService } from './locale/translateservice.js'
- import { Translation, TRANSLATION_PROVIDERS } from './locale/translations.js';
- import { TranslatePipe } from './locale/translatepipe.js';
-
- import { HomePageComponent } from './src/app.component.homepage';
-
- @NgModule({
- imports: [BrowserModule, ReactiveFormsModule],
- declarations: [HomePageComponent, TranslatePipe],
- exports: [TranslatePipe],
- bootstrap: [HomePageComponent],
- providers: [TRANSLATION_PROVIDERS, { provide: TranslateService, useClass: TranslateService },
- { provide: LOCALE_ID, deps: [TranslateService], useFactory: (TranslateService) => TranslateService.getLocale() }
- ]
- })
-
- export class AppModule { }
main.ts
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
-
- import { AppModule } from './app.module';
-
- const platform = platformBrowserDynamic();
- platform.bootstrapModule(AppModule);
Index.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>Angular2 - Localisation </title>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link href="../resources/style/bootstrap.css" rel="stylesheet" />
- <link href="../resources/style/style1.css" rel="stylesheet" />
-
- <script src="../resources/js/jquery-2.1.1.js"></script>
- <script src="../resources/js/bootstrap.js"></script>
-
- <script src="../node_modules/core-js/client/shim.min.js"></script>
- <script src="../node_modules/zone.js/dist/zone.js"></script>
- <script src="../node_modules/reflect-metadata/Reflect.js"></script>
- <script src="../node_modules/systemjs/dist/system.src.js"></script>
- <script src="../systemjs.config.js"></script>
- <script>
- System.import('app').catch(function (err) { console.error(err); });
- </script>
-
- <script>document.write('<base href="' + document.location + '" />');</script>
- </head>
- <body>
- <home-page>Loading</home-page>
- </body>
- </html>
Now, run the program. The output is shown below.