In this article, we will learn how we can use the internationalization library for Angular Transloco to lazy load translation files in our Angular application. There are two advantages to this approach. First, we make our initial bundle smaller, which will improve the application load time. Second, we are less exposed to merge conflicts.

Let’s see how easy it is to do it with Transloco 💪

Let’s say we have a user profile page. We want to create separate translation files for this page and load them only when the user navigates there.

First, we need to create a user-profile folder (or whatever name you choose); In it, we create a translation file for each language we want to support:

├─ i18n/

├─ en.json

├─ es.json

├─ profile-page/

├─ en.json

├─ es.json

In each file will add only the relevant translations for this page:

{

"title": "User Profile"

}

Let’s continue and create the UserProfile module and routes:

Adding the TRANSLOCO_SCOPE to the providers instruct Transloco load the corresponding scope based on the active language and merge it under the scope namespace into the active language translation object.

For example, if the active language is en, it will load the user-profile/en.json file, and will set the translation to be the following:

{

header: ‘’,

login: ‘’,

userProfile: {

title: ‘User Profile’

}

}

Now we can access each one of the user profile keys by using the userProfile namespace:

By default, the namespace will be the scope name (camel cased), but we can override it in two ways:

By using the config.scopeMapping config:

{

provide: TRANSLOCO_CONFIG,

useValue: {

defaultLang: 'en',

scopeMapping: {

'user-profile': 'profile'

}

}

}

By providing a custom alias name in the module/component scope provider:

{

provide: TRANSLOCO_SCOPE,

useValue: { scope: ‘user-profile’, alias: ‘profile’ }

}

Now we can access it through a custom name we provided instead of the original scope name (profile in our case):

If you liked this post, please 👏🏻 and share it!