Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 74 ยท Quality and Performance

Internationalization and Localization

Translate an Angular app with i18n attributes, $localize, ng extract-i18n, ICU plural and select messages and locale-aware pipes, and learn when runtime translation libraries fit better.

Internationalization (i18n) means building an app so it can support many languages and regions. Localization (l10n) means actually providing one: translated text, local number and date formats, and the right plural rules. Doing it late is painful, because every string, every date and every "1 item / 2 items" sentence is spread through your templates.

Angular has a built-in, compile-time i18n system: you mark text in templates and code, extract it into a translation file, have it translated, and build one app per language. This lesson walks through that workflow, then covers the locale-aware pipes, ICU messages for plurals and selects, and the main alternative: libraries that translate at runtime.

Real versus stand-in. The typescript, html and bash blocks are real Angular and its CLI, so they are read-only. The runnable examples are stand-ins: an ICU message formatter built on the browser-standard Intl.PluralRules, and a tiny tagged-template translator. Angular's real formatter and file formats are more complete.

Marking text in templates

Add the i18n attribute to any element whose text should be translated. It is an instruction to the compiler and disappears from the output:

HTML
<h1 i18n>Welcome back</h1>

<!-- a meaning, a description and a custom id help translators and keep ids stable -->
<button i18n="Save button on the profile form|Saves the profile@@profile.save">Save</button>

<!-- translate attributes with i18n-<attribute> -->
<img src="logo.svg" alt="Company logo" i18n-alt />

<!-- translate text without adding an element -->
<ng-container i18n>Last updated by {{ author() }}</ng-container>

The format of the attribute value is meaning|description@@id; every part is optional. The description and meaning are notes for translators (the same English word can need different translations in different contexts). The @@id gives the message a custom id. Without one, Angular derives an id from the text, so editing the English wording changes the id and the old translation no longer matches. Custom ids avoid that for messages you expect to edit.

Interpolations such as {{ author() }} become placeholders in the translation, so translators can move them around in the sentence.

Translating text in code

Text in TypeScript uses the $localize tagged template. It comes from the @angular/localize package, which ng add @angular/localize installs and wires up:

TypeScript
const greeting = $localize`:@@home.greeting:Hello, ${this.name()}!`;
const title = $localize`:Page title|The title of the dashboard page@@dashboard.title:Dashboard`;

The text between the first pair of colons holds the same meaning|description@@id metadata, and the rest is the message. Anything inside ${...} becomes a placeholder. Plain, non-tagged strings are never translated, so only wrap text a user will read.

The extract, translate, build workflow

flowchart LR
  A["Source code<br/>i18n attributes and $localize"] -- "ng extract-i18n" --> B["messages.xlf<br/>(source language)"]
  B -- "send to translators" --> C["messages.fr.xlf<br/>messages.de.xlf"]
  C -- "ng build with locales configured" --> D["dist/.../en-US/<br/>dist/.../fr/<br/>dist/.../de/"]
  D --> E["Server or CDN picks<br/>a folder per language"]

Translation happens at build time: each language becomes its own copy of the app.

The steps in practice:

Terminal
ng add @angular/localize
ng extract-i18n --output-path src/locale
# translators produce src/locale/messages.fr.xlf, messages.de.xlf, ...
ng build --localize

The locales are declared in angular.json:

JSON
{
  "projects": {
    "app": {
      "i18n": {
        "sourceLocale": "en-US",
        "locales": {
          "fr": { "translation": "src/locale/messages.fr.xlf" },
          "de": { "translation": "src/locale/messages.de.xlf" }
        }
      }
    }
  }
}

ng extract-i18n writes XLIFF by default, and it can also write other formats such as XLIFF 2, XMB or ARB (JSON); check ng extract-i18n --help for the --format choices. Each <trans-unit> in the file holds the source text and, once translated, a <target>. With --localize, the build produces one folder per locale. Your server or CDN then serves the right folder, usually under a path such as /fr/.

The big advantage of compile-time translation is speed: the final bundle contains plain strings with no lookup at runtime. The cost is one build and one deployment folder per language, and switching language means loading a different app, not just a different file.

ICU plurals and selects

Plural rules are surprisingly varied. English has two forms ("1 file", "2 files"). Russian has four categories (one, few, many, other), and Arabic has six. Concatenating count + ' files' cannot work for all of them. The ICU message format puts the whole sentence, with its alternatives, in one message so translators can supply the forms their language needs.

HTML
<span i18n>
  {count(), plural,
    =0 {No messages}
    =1 {One message}
    other {{{ count() }} messages}
  }
</span>

<span i18n>
  {gender(), select,
    female {She replied}
    male {He replied}
    other {They replied}
  }
</span>

A plural message matches an exact number with =0, =1 and so on, then falls back to the language's category (one, few, other...), and always needs an other case. A select message matches a string value and also needs other. Angular uses {{ ... }} inside a case for interpolation. The stand-in below parses simple ICU messages (without nesting) and picks the case with Intl.PluralRules, the same standard data browsers use.

TypeScript A small ICU plural and select formatter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the Russian lines: 1 and 21 share a form, 2 and 22 share another, and 11 uses a third. The rule is not "one or many", and that is the reason ICU messages exist. Never build sentences from pieces in code.

Locale-aware pipes

The date, currency, number and percent pipes (Pipes) format by the active locale, which comes from the LOCALE_ID token. In a localized build Angular sets it for you and loads the right locale data. In an app without the localized build, register the data yourself and provide the id:

TypeScript
import { LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';

registerLocaleData(localeDe);

export const appConfig = {
  providers: [{ provide: LOCALE_ID, useValue: 'de' }],
};
HTML
<p>{{ price | currency: 'EUR' }}</p>
<p>{{ today | date: 'longDate' }}</p>
<p>{{ ratio | percent }}</p>

The pipe gets the locale from LOCALE_ID by default, and you can also pass one per call. Currency codes stay explicit because the language does not tell you the money: a German user can still be shown US dollars. The stand-in below uses the browser Intl API, which does the same job with the same underlying data, and also shows a runtime translator built with a tagged template.

TypeScript Locale formats and a tiny tagged-template translator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The second column shows the main reason to use Intl or the pipes instead of manual formatting: separators, symbols and even digit grouping differ by locale. The translator output shows the fallback rule too: German has no inbox entry, so the source text is used. Real Angular reports missing translations at build time (as a warning by default), so you can catch gaps before release.

Runtime translation libraries

Angular's built-in approach does not fit every project. If users must switch language without reloading, if translations are edited by non-developers and should ship without a rebuild, or if you cannot afford a build and deploy per language, use a runtime library such as Transloco or ngx-translate. They load JSON files ({ "home.title": "Bienvenue" }) in the browser, look keys up with a pipe, directive or service, and can switch language on the fly.

Concern Built-in i18n Runtime library
Translation time Build time In the browser
Runtime cost None A lookup and a file download
Switch language without reload No Yes
Builds and deploy folders One per language One
ICU and locale pipes Built in Library-specific; pipes still use LOCALE_ID

Whichever you choose, the habits are the same: never concatenate translated fragments, give translators context, keep layouts flexible (German text is often much longer than English), and design for right-to-left languages with logical CSS properties such as margin-inline-start.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the i18n attribute do at build time?

    It is a compiler instruction. ng extract-i18n collects marked messages, and the attribute itself does not appear in the built page.
  2. 2. Why give important messages a custom id such as @@profile.save?

    Without a custom id, Angular derives the id from the text, so a reworded message gets a new id and loses its old translations.
  3. 3. Why use an ICU plural message instead of count + ' files'?

    Russian has one, few, many and other, and Arabic has six categories. One ICU message lets each language provide its own forms.
  4. 4. What is the main trade-off of Angular's built-in compile-time i18n?

    Translations are baked into the bundles, which is fast at runtime, but each locale is a separate build and deployment folder.
  5. 5. When would a runtime library like Transloco be the better choice?

    Runtime libraries load translations in the browser, so switching is instant and translation files can be updated independently of the build.

Summary

  • Mark template text with i18n (and attributes with i18n-attr), and code strings with $localize; add meanings, descriptions and custom ids for translators and stable ids.
  • ng extract-i18n creates the source translation file; translators fill in targets; ng build --localize makes one app per locale configured in angular.json.
  • ICU plural and select messages keep whole sentences together so each language can use its own plural categories.
  • date, currency, number and percent pipes follow LOCALE_ID; register locale data when you do not use a localized build.
  • Pick runtime libraries (Transloco, ngx-translate) when you need instant language switching or translation updates without a rebuild.

Next: Angular Material and the CDK.