Tag Archives: i18n

Angular2 Internationalization (i18n)

When you build frontend interfaces for the web, you often have to provide support for different languages, locales and timezones (generally called internationalization or short i18n in computer science). With Angular2 you can use the module “ng2-translate” to provide browser language detection and to resolve internationalized text fragments. In this article I will show how to use language files for Angular2.

Include Angular2 translation module

The ng2-translate  module can be simply added to your project via npm by calling:

Next you have to add the module to your Angular2 application module, by including  TranslateModule  from ng2-translate :

import {NgModule} from ‘@angular/core’; import {HttpModule} from ‘@angular/http’; import {TranslateModule} from ‘ng2-translate’; @NgModule({ imports: [ BrowserModule, HttpModule, TranslateModule.forRoot() ], bootstrap: [AppComponent] }) export class AppModule { }

Provide Language files

By default, the ng2-translate module loads the translated texts in JSON Format from the path "i18n/*.json" , where "*"  is the selected language (de, en, …).

The translation keys are organized in a JSON hierarchy and can be grouped thematically with this feature. So take this example translation file:

There are now the translation keys “ExamplePage.Title”, “ExamplePage.Description”, “AnotherPage.Title”, “AnotherPage.Info” and “AnotherPage.Subsection1.SocialMedia” available.

You need to provide such a file for each language you want to support.

Use in your Angular2 application

In order to enable the translation feature, you first have to initialize the ng2-translation service in your application, e.g. in the initializer of your app component. You can configure which languages you support and which is the default language. You also can use browser detection to get the preferred language of your user agent.

To insert translated texts in your Angular2 template, simply use the “translate” pipe. Put the translation key as input of the pipe, then add “|translate”.

You can also query translations from the TranslationService directly (with the "get"  method), but be aware, that the translation resolution is asynchronous by default (because it could be required to fetch the translation file on the first encounter). Therefore queries of translations always return Observables, unless you force instant evaulation with the "instant"  method (which will fail if the language file is not loaded, yet).