Translation and languages in the JSS Angular sample app

Version: 22.x

Angular applications created with JSS can display data in multiple languages.

Adding a new language

The Angular sample application contains example content in both English and Danish, and in disconnected mode you can easily switch languages. To import the Danish language layer for use in other modes, you must deploy the items:

RequestResponse
jss deploy items --language da-DK -c -d
Important

To deploy an alternate language to Sitecore, the language must be first registered in Sitecore. An error occurs when importing an unregistered language.

Using the ngx-translate library

To dynamically load and utilize the Sitecore dictionary, the Angular sample uses the ngx-translate library, rather than the built-in compile-time Angular translation support.

You can use other libraries or approaches, but this library's ability to consume custom TranslateLoader implementations makes it easy to use with the Sitecore dictionary both client-side and server-side.

You can find the initialization for ngx-translate in the main app component in src/app/app.component.ts. This includes logic to switch displayed languages based on the current language state in JssContextService, allowing the ngx-translate library to synchronize the language state with the language in the current route.

The loaders for the ngx-translate library are initialized differently for client rendering and server rendering, in src/app/app.module.ts and src/app/app.server.module.ts, respectively.

There are several mechanisms of using translated values with the ngx-translate library. See the ngx-translate documentation for more information.

Translation loaders

The JSS Angular sample application defines and uses several translation loaders. They reside in the src/app/i18n directory.

JssTranslationLoaderService

This implementation loads the Sitecore dictionary from the Dictionary Service provided by Headless Services. It serves as a fallback during both client and server rendering.

JssTranslationServerLoaderService

This implementation attempts to load the dictionary from the viewBag data that Sitecore provides during server rendering through the JSS_SERVER_TO_SSR injection token. When executing JSS applications, Sitecore provides the dictionary in the view bag by default as a convenience. If the dictionary is not found, the loader attempts to obtain the dictionary from a fallback loader (as configured, the JssTranslationLoaderService). Any obtained dictionary is also placed in TransferState for consumption by the client application.

JssTranslationClientLoaderService

This implementation attempts to load the dictionary from TransferState, and falls back to a provided fallback loader (as configured, the JssTranslationLoaderService).

Do you have some feedback for us?

If you have suggestions for improving this article,