Originally published at shahar.kazaz
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:
const routes: Routes = [
{
path: '',
component: UserProfileComponent
}
];
@NgModule({
declarations: [UserProfileComponent],
providers: [{ provide: TRANSLOCO_SCOPE, useValue: 'user-profile' }],
imports: [CommonModule, RouterModule.forChild(routes), TranslocoModule]
})
export class UserProfileModule {}
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:
<ng-container *transloco="let t">
{{ t('userProfile.title') }}
{{ t('title') }}
</ng-container>
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):
<ng-container *transloco="let t">
{{ t('profile.title') }}
{{ t('title') }}
</ng-container>
Here is some more great content about Transloco:
Top comments (0)