How to internationalize your Angular application?

Yesterday, we touched on how to change the locale of our Angular applications. The next step is to fully internationalize our apps by translating all text into different languages.

While Angular has its localization implementation to internationalize applications, the most popular library used for such a task is ngx-translate.

Why not use Angular’s internal implementation? The main reason is that Angular builds one version of your application per locale. As a result, if you have to support 20 different locales, your Angular build would output 20 different applications. This means that changing the site would result in a complete reload of the application. This also means that changing a translation requires a complete rebuild and redeploy of the application.

ngx-translate is much more flexible because it relies on pipes, directives, and services to translate our text at runtime instead of build-time. Here are some examples:

With TranslateService:

With TranslatePipe:

With TranslateDirective:

Translations come from specific files where translation keys ("HELLO" in my example) are mapped to actual values in each language. ngx-translate supports different formats out of the box (such as JSON and PO).

Here is an example of English translations stored in en.json:

And the same translations in French in fr.json:

All we have to do is indicate where the translation files are located and ngx-translate will download them as needed based on the locale.

Defining which languages are supported as well as which one to use by default can all be done with the TranslateService from the library:

You can see a live example of ngx-translate in Stackblitz here. If you want to try it, you can use my ngx-translate step-by-step tutorial.

How to change the locale of your Angular application?

A locale is a combination of country and language, such as fr-CA for French spoken in Canada or en-US for English spoken in the US. Locales matter when you want to create an application that works all around the globe.

For instance, let’s take the following sentence in American English for the US:

On 04/01/2023, the price of this item was $2,056.23

The same sentence in French for France would be:

Le 01/04/2023, le prix de cet article était 2 056,23 €

As you can see, everything is different. Currency, number format, date format, and of course, language. Knowing all of these differences between locales would be a complex task. Fortunately for us, Angular knows about most locales, and all pipes and formatting functions use that locale to format dates/numbers/currencies correctly.

To support different locales, we have to import all of them in main.ts:

Then you can configure your providers to set a default LOCALE_ID:

And just like that, the expression {{ 2056.23 | number }} would display 2 056,23 instead of 2,056.23 (code example here). So our pipes will use that default locale from now on.