How to implement localization in Angular 10

Darshan Trambadiya

Oct 06, 2020 | 6 min read

Internationalization (i18n) is the process of designing and preparing your app to be usable in different locales around the world. Localization is the process of building versions of your app for different locales, including extracting text for translation into different languages, and formatting data for particular locales.

A locale identifies a region (such as a country) in which people speak a particular language or language variant. The locale determines the formatting and parsing of dates, times, numbers, and currencies as well as measurement units and the translated names for time zones, languages, and countries.

Prerequisites


To prepare your app for translations, you should have a basic understanding of the following:

Steps to localize your app

Create new project with Angular CLI by running

ng new i18nDemo

For localization demo, Update app.component.html with below code

<h1 i18n> Localization Demo in Angular using i18n</h1>
<h3 i18n="@@myName"> Hello, My name is Darshan</h3>
<p>This text will remain same in all languages</p>
<hr />
<ng-container *ngFor="let language of languageList">
  <a href="/{{language.code}}/">
    <button class="button">{{language.label}}</button>
  </a>
</ng-container>

Update app.component.ts with below code

import { Component, LOCALE_ID, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'i18nDemo';
  languageList = [
    { code: 'en-US', label: 'English' },
    { code: 'hi', label: 'हिंदी' },
    { code: 'es', label: 'Spanish' },
  ];
  constructor(@Inject(LOCALE_ID) protected localeId: string) {}
}

Add the localize package @angular/localize with Angular CLI by running

ng add @angular/localize

This command updates your project's package.json and polyfills.ts files to import the @angular/localize package.

Now create translation file with Angular CLI by running

ng xi18n --output-path src/locale

This will create messages.xlf translation file which looks like

<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
  <file source-language="en-US" datatype="plaintext" original="ng2.template">
    <body>
      <trans-unit id="cd299a9a7bd5d4962e27040b729b21cb4eb7807a" datatype="html">
        <source>Localization Demo in Angular using i18n</source>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">1</context>
        </context-group>
      </trans-unit>
      <trans-unit id="myName" datatype="html">
        <source>Hello, My name is Darshan</source>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">2</context>
        </context-group>
      </trans-unit>
    </body>
  </file>
</xliff>

We will use Google Translate for translation, Now create Spanish messages.es.xlf translation file which looks like

<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
  <file source-language="en-US" datatype="plaintext" original="ng2.template">
    <body>
      <trans-unit id="cd299a9a7bd5d4962e27040b729b21cb4eb7807a" datatype="html">
        <source>Localization Demo in Angular using i18n</source>
        <target>Demostración de localización en angular usando i18n</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">1</context>
        </context-group>
      </trans-unit>
      <trans-unit id="myName" datatype="html">
        <source>Hello, My name is Darshan</source>
        <target>Hola, mi nombre es Darshan</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">2</context>
        </context-group>
      </trans-unit>
    </body>
  </file>
</xliff>

Now create Hindi messages.hi.xlf translation file which looks like

<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
  <file source-language="en-US" datatype="plaintext" original="ng2.template">
    <body>
      <trans-unit id="cd299a9a7bd5d4962e27040b729b21cb4eb7807a" datatype="html">
        <source>Localization Demo in Angular using i18n</source>
        <target>I18n का उपयोग कर कोणीय में स्थानीयकरण डेमो</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">1</context>
        </context-group>
      </trans-unit>
      <trans-unit id="myName" datatype="html">
        <source>Hello, My name is Darshan</source>
        <target>हेलो, मेरा नाम दर्शन है</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">2</context>
        </context-group>
      </trans-unit>
    </body>
  </file>
</xliff>

Now Define locales in the build configuration. So update angular.json file like

{
  ...,
  "projects": {
    "i18nDemo": {
      ...,
      "i18n": {
        "sourceLocale": "en-US",
        "locales": {
          "es": {
            "translation": "src/locale/messages.es.xlf"
          },
          "hi": {
            "translation": "src/locale/messages.hi.xlf"
          }
        }
      },
      "architect": {
        "build": {
          ...,
          "options": {
            ...,
            "localize": true
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            },
            "es": {
              "localize": ["es"]
            },
            "hi": {
              "localize": ["hi"]
            }
          }
        },
        "serve": {
          ...,
          "configurations": {
            "production": {
              "browserTarget": "i18nDemo:build:production"
            },
            "es": {
              "browserTarget": "i18nDemo:build:es"
            },
            "hi": {
              "browserTarget": "i18nDemo:build:hi"
            }
          }
        }
      }
    }
  },
  "defaultProject": "i18nDemo"
}

Now update script section of package.json like

{
  "name": "i18n-demo",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --configuration=production",
    "start:es": "ng serve --configuration=es",
    "build": "ng build",
    "build:prod": "ng build --configuration=production",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "dependencies": {
    ...
  },
  "devDependencies": {
    ...
  }
}

Now we can serve the app with different locales by running npm run start OR npm run start:es

We can build the app including all locales by running npm run build OR npm run build:prod

To test build, we will use http-server npm package so install it with npm i -g http-server. Now go to your project path & run http-server dist/i18nDemo.

Conclusion

This is how we can use multiple locales in our Angular 10 application.