Skip to main content

Angular i18n

Angular's built-in i18n system marks translatable strings in templates, extracts them to XLIFF files, and compiles separate builds per locale.

Mark Strings in Templates

<!-- Static text -->
<h1 i18n="@@app.title">Album Store</h1>

<!-- With meaning and description -->
<p i18n="Page heading|Shown on the homepage@@home.heading">
Welcome to the store
</p>

<!-- Attribute -->
<input i18n-placeholder="@@search.placeholder" placeholder="Search…" />

<!-- Named ID (@@id makes re-extraction stable) -->
<button i18n="@@cart.add">Add to cart</button>

Extract Messages

ng extract-i18n --format xlf2 --output-path src/locale

Generated src/locale/messages.xlf:

<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en-US">
<file id="ngi18n" original="ng:localize">
<unit id="app.title">
<segment>
<source>Album Store</source>
</segment>
</unit>
</file>
</xliff>

Translate (French)

Copy and rename:

cp src/locale/messages.xlf src/locale/messages.fr.xlf

Add <target> inside each <segment>:

<unit id="app.title">
<segment>
<source>Album Store</source>
<target>Boutique d'Albums</target>
</segment>
</unit>

Plural and Select

<!-- Plural -->
<p i18n="@@cart.items">
{itemCount, plural,
=0 {No items}
=1 {1 item}
other {{{itemCount}} items}
}
</p>

<!-- Select -->
<span i18n="@@format.type">
{format, select,
vinyl {Vinyl}
cd {CD}
other {Digital}
}
</span>

French translation for plural:

<unit id="cart.items">
<segment>
<source>{itemCount, plural, =0 {No items} =1 {1 item} other {{{itemCount}} items}}</source>
<target>{itemCount, plural, =0 {Aucun article} =1 {1 article} other {{{itemCount}} articles}}</target>
</segment>
</unit>

Configure angular.json

{
"projects": {
"my-app": {
"i18n": {
"sourceLocale": "en-US",
"locales": {
"fr": {
"translation": "src/locale/messages.fr.xlf"
}
}
},
"architect": {
"build": {
"configurations": {
"fr": { "localize": ["fr"] },
"production": { "localize": true }
}
}
}
}
}
}

Build Localized Bundles

# All locales
ng build --localize

# Single locale
ng build --configuration=fr

Output:

dist/my-app/browser/
├── en-US/
└── fr/

Serve in Development (Single Locale)

ng serve --configuration=fr

Key Points

ConceptDetails
i18n attributeMarks element content for translation
i18n-{attr}Marks an HTML attribute
@@idStable translation unit ID (recommended)
XLIFF formatXLF or XLF2 (prefer XLF2)
ng extract-i18nGenerates the source message file
ng build --localizeCompiles one bundle per locale