{ "id": "guide/i18n", "title": "Localizing your app", "contents": "\n\n\n
Internationalization (i18n) is the process of designing and preparing your app to be usable in different locales around the world.\nLocalization 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.
\nA 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.
\nCreate an adaptable user interface for all of your target locales that takes into consideration the differences in spacing for different languages. For details, see How to approach internationalization.
\nUse Angular to internationalize your app:
\nAfter preparing your app for an international audience, use the Angular CLI to localize your app by performing the following tasks:
\n To explore the sample app with French translations used in this guide, see the
To prepare your app for translations, you should have a basic understanding of the following:
\nTo localize your app, follow these general steps:
\nWhile following these steps, you can explore the translated example app.
\nThe following are optional practices that may be required in special cases:
\nTo take advantage of Angular's localization features, use the Angular CLI to add the @angular/localize
package to your project:
This command updates your project's package.json
and polyfills.ts
files to import the @angular/localize
package.
For more information about package.json
and polyfill packages, see Workspace npm dependencies.
If @angular/localize
is not installed, the Angular CLI may generate an error when you try to build a localized version of your app.
Refer to a locale using the Unicode locale identifier (ID), which specifies the language, country, and an optional code for further variants or subdivisions.
\nThe ID consists of a language identifier, such as en
for English or fr
for French, followed by a dash (-
) and a locale extension, such as US
for the United States or CA
for Canada.\nFor example, en-US
refers to English in the United States, and fr-CA
refers to French in Canada.\nAngular uses this ID to find the correct corresponding locale data.
Many countries, such as France and Canada, use the same language (French, identified as fr
) but differ in grammar, punctuation, and formats for currency, decimal numbers, and dates.\nUse a more specific locale ID, such as French for Canada (fr-CA
), when localizing your app.
Angular by default uses en-US
(English in the United States) as your app's source locale.
The Angular repository includes common locales.\nYou can change your app's source locale for the build by setting the source locale in the sourceLocale
field of your app's workspace configuration file (angular.json
).\nThe build process (described in Merge translations into the app in this guide) uses your app's angular.json
file to automatically set the LOCALE_ID
token and load the locale data.
Angular provides the following built-in data transformation pipes that use the LOCALE_ID
token to format data according to the locale's rules:
DatePipe
: Formats a date value.CurrencyPipe
: Transforms a number to a currency string.DecimalPipe
: Transforms a number into a decimal number string.PercentPipe
: Transforms a number to a percentage string.For example, {{today | date}}
uses DatePipe
to display the current date in the format for the locale in LOCALE_ID
.
To override the value of LOCALE_ID
, add the locale
parameter.\nFor example, to force the currency to use en-US
no matter which language-locale you set for LOCALE_ID
, use this form: {{amount | currency : 'en-US'}}
.
To translate your app's templates, you need to prepare the text for a translator or translation service by marking text, attributes, and other elements with the Angular i18n
attribute.\nFollow these general steps:
title
attribute.Mark the static text messages in your component templates for translation using the i18n
attribute.\nPlace it on every element tag with fixed text to be translated.
For example, the following <h1>
tag displays a simple English language greeting, \"Hello i18n!\"
To mark the greeting for translation, add the i18n
attribute to the <h1>
tag.
i18n
is a custom attribute, recognized by Angular tools and compilers.\nAfter translation, the compiler removes it. It is not an Angular directive.
To translate a text message accurately, the translator may need additional information or context.\nAdd a description of the text message as the value of the i18n
attribute, as shown in the following example:
The translator may also need to know the meaning or intent of the text message within this particular app context, in order to translate it the same way as other text with the same meaning.\nStart the i18n
attribute value with the meaning and\nseparate it from the description with the |
character: <meaning>|<description>
.
For example, you can add the meaning that this <h1>
tag is a site header that needs to be translated the same way not only when used as a header, but also when referred to from another section of text:
As a result, any text marked with site header
as the meaning is translated exactly the same way.
The Angular extraction tool (described in Work with translation files in this guide) generates a translation unit entry for each i18n
\nattribute in a template.\nIt assigns each translation unit a unique ID based on the meaning and description.
The same text elements with different meanings are extracted with separate IDs.\nFor example, if the word \"right\" appears with the meaning correct
(as in \"You are right\") in one place, and with the meaning direction
(as in \"Turn right\") in another place, the word is translated differently and merged back into the app as different translation entries.
If the same text elements have different descriptions but the same meaning, they are extracted only once, with only one ID. That one translation entry is merged back into the app wherever the same text elements appear.
\nWhile you can translate non-displayed text using a <span>
tag, you are creating a new DOM element. To avoid doing so, wrap the text in an <ng-container>
element, which is transformed into a non-displayed HTML comment as shown in this example:
HTML attributes such as title
include text that should be translated along with the rest of the displayed text in the template.\nThe following example shows an image with a title
attribute:
To mark an attribute for translation, add i18n-
attribute in which attribute is the attribute to translate.\nThe following example shows how to mark the\ntitle
attribute on the img
tag by adding i18n-title
:
You can use i18n-
attribute with any attribute of any element.\nYou also can assign a meaning, description, and custom ID with the i18n-
attribute=\"<meaning>|<description>@@<id>\"
syntax.
Different languages have different pluralization rules and grammatical constructions that can make translation difficult.\nTo simplify translation, use International Components for Unicode (ICU) clauses with regular expressions, such as plural
to mark the uses of plural numbers, and select
to mark alternate text choices.
The ICU clauses adhere to the ICU Message Format specified in the CLDR pluralization rules.
\nUse the plural
clause to mark expressions that may not be meaningful if translated word-for-word.
For example, if you want to display \"updated x minutes ago\" in English, you may want to display \"just now\", \"one minute ago\", or \"x minutes ago\" (with x as the actual number).\nOther languages might express this cardinality differently.\nThe following example shows how to use a plural
clause to express these three options:
In the above example:
\nThe first parameter, minutes
, is bound to the component property (minutes
), which determines the number of minutes.
The second parameter identifies this as a plural
translation type.
The third parameter defines a pattern of pluralization categories and their matching values:
\n=0 {just now}
.=1 {one minute}
.other {{{minutes}} minutes ago}
.\nYou can use HTML markup and interpolations such as {{{minutes}}
with the plural
clause in expressions.{}
).Pluralization categories include (depending on the language):
\n=0
(or any other number)zero
one
two
few
many
other
Many locales don't support some of the pluralization categories.\nFor example, the default locale (en-US
) and other locales (such as es
) have very simple plural()
functions that don't support the few
category.\nThe following shows the en-US plural()
function:
The function will only ever return 1 (one
) or 5 (other
).\nThe few
category will never match.\nIf none of the pluralization categories match, Angular will try to match other
.\nUse other
as the standard fallback for a missing category.
For more information about pluralization categories, see Choosing plural category names in the CLDR - Unicode Common Locale Data Repository.
\nIf you need to display alternate text depending on the value of a variable, you\nneed to translate all of the alternates.
\nThe select
clause, similar to the plural
clause, marks choices for alternate text based on your defined string values.\nFor example, the following clause in the component template binds to the component's gender
property, which outputs one of the following string values: \"male\", \"female\" or \"other\".\nThe clause maps those values to the appropriate translations:
You can also nest different clauses together, such as the plural
and select
clauses in the following example:
After preparing a template for translation, use the Angular CLI extract-i18n
command to extract the marked text in the template into a source language file.\nThe marked text includes text marked with i18n
and attributes marked with i18n-
attribute as described in the previous section.\nFollow these steps:
To extract the source language file, open a terminal window, change to the root directory of your app project, and run the following CLI command:
\nThe extract-i18n
command creates a source language file named messages.xlf
in your project's root directory using the XML Localization Interchange File Format (XLIFF, version 1.2).
Use the following extract-i18n
command options to change the source language file location, format, and file name:
--output-path
: Change the location.--format
: Change the format.--outFile
: Change the file name.Note: The --i18n-locale
option is deprecated.\nAngular 9 uses the source locale configured in your app's workspace configuration file (angular.json
).
To create a file in the src/locale
directory, specify the output path as an option, as shown in the following example:
The extract-i18n
command can read and write files in three translation formats:
Specify the translation format explicitly with the --format
command option, as shown in the following examples:
XLIFF files use the extension .xlf
.\nThe XMB format generates .xmb
source language files but uses.xtb
(XML Translation Bundle: XTB) translation files.
To change the name of the source language file generated by the extraction tool, use\nthe --outFile
command option:
The ng extract-i18n
command (with no options) generates a source language file named messages.xlf
in the project src
folder.\nCreate translation files for each language by copying the source language file.\nTo avoid confusion with multiple translations, you should organize the language translation files by locale in a dedicated locale
folder under src/
.\nUse a filename extension that matches the associated locale, such as messages.fr.xlf
.
For example, to create a French translation file, follow these steps:
\nmessages.xlf
source language file.src/locale
folder.messages.fr.xlf
for the French language (fr
) translation.\nSend this translation file to the translator.Repeat the above steps for each language you want to add to your app.
\n\nUnless you are fluent in the language and have the time to edit translations, you would likely send each translation file to a translator, who would then use an XLIFF file editor to create and edit the translation.
\nTo demonstrate this process, see the messages.fr.xlf
file in the
messages.fr.xlf
and find the first <trans-unit>
element. This is a translation unit, also known as a text node, representing the translation of the <h1>
greeting tag that was previously marked with the i18n
attribute:\n\n)\">\n<trans-unit id=\"introductionHeader\" datatype=\"html\">\n <source>Hello i18n!</source>\n <note priority=\"1\" from=\"description\">An introduction header for this sample</note>\n <note priority=\"1\" from=\"meaning\">User welcome</note>\n</trans-unit>\n\n \nThe
\nid=\"introductionHeader\"\"
is a custom ID, but without the@@
prefix required in the source HTML.
<source>...</source>
element in the text node, rename it target
, and then replace its content with the French text:\n\n, after translation)\">\n<trans-unit id=\"introductionHeader\" datatype=\"html\">\n <source>Hello i18n!</source>\n <target>Bonjour i18n !</target>\n <note priority=\"1\" from=\"description\">An introduction header for this sample</note>\n <note priority=\"1\" from=\"meaning\">User welcome</note>\n</trans-unit>\n\n \nIn a more complex translation, the information and context in the description and meaning elements described previously would help you choose the right words for translation.
\n
\n\n)\">\n<trans-unit id=\"ba0cc104d3d69bf669f97b8d96a4c5d8d9559aa3\" datatype=\"html\">\n <source>I don't output any element</source>\n <target>Je n'affiche aucun élément</target>\n</trans-unit>\n<trans-unit id=\"701174153757adf13e7c24a248c8a873ac9f5193\" datatype=\"html\">\n <source>Angular logo</source>\n <target>Logo d'Angular</target>\n</trans-unit>\n\n \n
Don't change the IDs for translation units.\nEach id
is generated by Angular and depends on the content of the template text and its assigned meaning.\nIf you change either the text or the meaning, then the id
changes.\nFor more about managing text updates and IDs, see the previous section on custom IDs.
The plural
and select
ICU expressions are extracted as additional messages, so you must translate them separately.
To translate a plural
, translate its ICU format match values as shown in the following example:
just now
one minute ago
<x id=\"INTERPOLATION\" equiv-text=\"{{minutes}}\"/> minutes ago
You can add or remove plural cases as needed for each language.
\nFor language plural rules, see\nCLDR plural rules.
\nAngular also extracts alternate select
ICU expressions as separate translation units.\nThe following shows a select
ICU expression in the component template:
In this example, Angular extracts the expression into two translation units. The first contains the text outside of the select
clause, and uses a placeholder for select
(<x id=\"ICU\">
):
When translating the text, you can move the placeholder if necessary, but don't remove it.\nIf you remove the placeholder, the ICU expression will not appear in your translated app.
\nThe second translation unit contains the select
clause:
The following example shows both translation units after translating:
\nAngular treats a nested expression in the same manner as an alternate expression, extracting it into two translation units. The first contains the text outside of the nested expression:
\nThe second translation unit contains the complete nested expression:
\nThe following example shows both translation units after translating:
\nTo merge the completed translations into the app, use the Angular CLI to build a copy of the app's distributable files for each locale.\nThe build process replaces the original text with translated text, and sets the LOCALE_ID
token for each distributable copy of the app.\nIt also loads and registers the locale data.
After merging, you can serve each distributable copy of the app using server-side language detection or different subdirectories, as described in the next section about deploying multiple locales.
\nThe build process uses ahead-of-time (AOT) compilation to produce a small, fast,\nready-to-run app. With Ivy in Angular version 9, AOT is used by default for both\ndevelopment and production builds, and AOT is required to localize component templates.
\nFor a detailed explanation the build process, see Building and serving Angular apps.\nThis build process works for translation files in the .xlf
format or in another format that Angular understands, such as .xtb
.
Ivy does not support merging i18n translations when using JIT mode.\nIf you disable Ivy and are using JIT mode, see merging with the JIT compiler.
\nTo build a separate distributable copy of the app for each locale, define the locales in the build configuration in your project's workspace configuration file angular.json
.\nThis method shortens the build process by removing the requirement to perform a full app build for each locale.
You can then generate app versions for each locale using the \"localize\"
option in angular.json
. You can also build from the command line using the Angular CLI build
command with the --localize
option.
You can optionally apply specific build options for just one locale for a custom locale configuration.
\nUse the i18n
project option in your app's build configuration file (angular.json
) to define locales for a project.\nThe following sub-options identify the source language and tell the compiler where to find supported translations for the project:
sourceLocale
: The locale you use within the app source code (en-US
by default)locales
: A map of locale identifiers to translation filesFor example, the following excerpt of an angular.json
file sets the source locale to en-US
and provides the path to the fr
(French) locale translation file:
To use your locale definition in the build configuration, use the \"localize\"
option in angular.json
to tell the CLI which locales to generate for the build configuration:
\"localize\"
to true
for all the locales previously defined in the build configuration.\"localize\"
to an array of a subset of the previously-defined locale identifiers to build only those locale versions.\"localize\"
to false
to disable localization and not generate any locale-specific versions.Note: Ahead-of-time (AOT) compilation is required to localize component templates.\nIf you changed this setting, set \"aot\"
to true
in order to use AOT.
The following example shows the \"localize\"
option set to true
in angular.json
so that all locales defined in the build configuration are built:
Due to the deployment complexities of i18n and the need to minimize rebuild time, the development server only supports localizing a single locale at a time.\nSetting the \"localize\"
option to true
will cause an error when using ng serve
if more than one locale is defined.\nSetting the option to a specific locale, such as \"localize\": [\"fr\"]
, can work if you want to develop against a specific locale (such as fr
).
The CLI loads and registers the locale data, places each generated version in a locale-specific directory to keep it separate from other locale versions, and puts the directories within the configured outputPath
for the project.\nFor each application variant the lang
attribute of the html
element is set to the locale.\nThe CLI also adjusts the HTML base HREF for each version of the app by adding the locale to the configured baseHref
.
You can set the \"localize\"
property as a shared configuration that all the configurations effectively inherit (or can override).
You can also use the --localize
option with the ng build
command and your existing production
configuration.\nThe CLI builds all locales defined in the build configuration, which is similar to setting the \"localize\"
option to true
as described in the previous section.
To apply specific build options to only one locale, you can create a custom locale-specific configuration by specifying a single locale as shown in the following example:
\nYou can then pass this configuration to the ng serve
or ng build
commands.\nThe following shows how to serve the French language file created in the example for this guide:
You can use the CLI development server (ng serve
), but only with a single locale.
For production builds, you can use configuration composition to execute both configurations:
\nWhen a translation is missing, the build succeeds but generates a warning such as\nMissing translation for message \"foo\"
. You can configure the level of warning that is generated by the Angular compiler:
error
: Throw an error. If you are using AOT compilation, the build will fail.\nIf you are using JIT compilation, the app will fail to load.warning
(default): Show a Missing translation
warning in the console or shell.ignore
: Do nothing.Specify the warning level in the options
section for the build
target of your Angular CLI configuration file (angular.json
). The following example shows how to set the warning level to error
:
If myapp
is the directory containing your app's distributable files, you would typically make available different versions for different locales in locale directories such as myapp/fr
for the French version and myapp.com/es
for the Spanish version.
The HTML base
tag with the href
attribute specifies the base URI, or URL, for relative links. If you set the \"localize\"
option in angular.json
to true
or to an array of locale IDs, the CLI adjusts the base href
for each version of the app by adding the locale to the configured \"baseHref\"
. You can specify the \"baseHref\"
for each locale in your workspace configuration file (angular.json
), as shown in the following example, which sets \"baseHref\"
to an empty string:
You can also use the CLI --baseHref
option with ng build
to declare the base href
at compile time.
Typical deployment of multiple languages serve each language from a different subdirectory.\nUsers are redirected to the preferred language defined in the browser using the\nAccept-Language
HTTP header. If the user has not defined a preferred language,\nor if the preferred language is not available, then the server falls back to the default language.\nUsers can change the language by navigating to other subdirectories, which often occurs using a\nmenu implemented in the application.
For more information on how to deploy apps to a remote server, see Deployment.
\nThe following is an example of an Nginx configuration.
\nThe following is an example of an Apache configuration.
\nThe following tabs show the example app and its translation files:
\nThe following are optional practices that may be required in special cases:
\nAngular already contains locale data for en-US
.\nThe Angular CLI automatically includes the locale data and sets the LOCALE_ID
value when you use the --localize
option with ng build
.
To manually set an app's source locale to one other than the automatic value, follow these steps:
\nLOCALE_ID
token.\nThe following example sets the value of LOCALE_ID
to fr
(French):Angular will automatically include locale data if you configure the locale using the --localize
option with ng build
CLI command.
The Angular repository files (@angular/common/locales
) contain most of the locale data that you need, but some advanced formatting options require additional locale data.\nGlobal variants of the locale data are available in @angular/common/locales/global
.\nThe following example imports the global variants for French (fr
):
The Angular extractor generates a file with a translation unit entry for each i18n
\nattribute in a template.\nAs described previously (in How meanings control text extraction and merging), Angular assigns each translation unit a unique ID such as the following:
When you change the translatable text, the extractor generates a new ID for that translation unit.\nIn most cases a text change would also require a change to the translation.\nTherefore, using a new ID keeps the text change in sync with translations.
\nHowever, some translation systems require a specific form or syntax for the ID.\nTo address this requirement, you can mark text with custom IDs.\nWhile most developers don't need to use custom IDs, some may want to use IDs that have a unique syntax to convey additional metadata (such as the library, component, or area of the app in which the text appears).
\nSpecify a custom ID in the i18n
attribute by using the prefix @@
.\nThe following example defines the custom ID introductionHeader
:
When you specify a custom ID, the extractor generates a translation unit with the custom ID:
\nIf you change the text, the extractor does not change the ID.\nAs a result, you don't have to take the extra step of updating the translation.\nThe drawback of using custom IDs is that if you change the text, your translation may be out-of-sync with the newly changed source text.
\nUse a custom ID in combination with a description and a meaning to further help the translator.\nThe following example includes a description, followed by the custom id
:
The following example adds a meaning:
\nBe sure to define custom IDs that are unique.\nIf you use the same ID for two different text elements, the extraction tool extracts only the first one, and Angular uses its translation in place of both original text elements.
\nFor example, in the following code the same custom ID myId
is defined for two different text elements:
The following shows the translation to French:
\nBoth elements now use the same translation (Bonjour
) because they were defined with the same custom ID: