question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to load separate translation files per module

See original GitHub issue

I’m submitting a … (check one with “x”)

[ ] bug report => check the FAQ and search github for a similar issue or PR before submitting
[x] support request => check the FAQ and search github for a similar issue before submitting
[ ] feature request

Expected/desired behavior Our application is very large and we don’t want the user to download all translations when they may only use a subset of the available modules. In some places the user must also be able to switch languages. Is there a way to load only the translations for the modules the user has access to? I’ve seen #22, but it doesn’t seem to have arrived at a final solution.

@nchutchind / @ollwenjones, I would love to hear about either of your solutions if you ever arrived at one?

What is the motivation / use case for changing the behavior? To prevent users from downloading resources they don’t require and allow dynamically switching languages at runtime

Please tell us about your environment: angular-cli@1.0.0-beta.26 generated so no access to webpack config etc

  • ng2-translate version: latest
  • Angular version: 2.4.5
  • Language: TypeScript 2.1.5

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:14 (4 by maintainers)

github_iconTop GitHub Comments

5reactions
jlberrocalcommented, May 26, 2017

@uberspeck i did something similar but using require on each lazy loaded module i have this

export class UsersModule {
    constructor(translate: TranslateService) {
        let lang = translate.getBrowserLang();
        let i18n = require(`./i18n/${lang}.json`);

        translate.setTranslation(lang, i18n, true);
    }
}

BTW for do that i did a PR for allow deep merge of objects

5reactions
uberspeckcommented, May 26, 2017

@AlwaysAbhl001, i’ve created a simple service to load translations for each module/component…

/app/shared/services/translation-loader.service.ts

import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

export interface ILocale {
  lang: string;
  data: Object;
}

@Injectable()
export class TranslationLoaderService {

  constructor(
    private translate: TranslateService
  ) { }

  public loadTranslations(...args: ILocale[]): void {
    const locales = [...args];
    locales.forEach( (locale) => {
      /* 
        use setTranslation() with the third argument set to true to append
        translations instead of replacing them
      */
      this.translate.setTranslation(locale.lang, locale.data, true); 
    });
  }

}

…then create the language files. You could use a different shape here if you wish.

/app/app.en.ts

export const locale = {
  "lang": "en",
  "data": {
    "app": { // <= namespace for module/component translations
      "title": "My Big Title",
      "archived": "Archived",
      "inactive": "Inactive",
      "delete":"Delete",
      ...
      }
    }
  }
}

…I then configure translation in the root module and load the root translation files…

/app/app.module.ts

...
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { TranslationLoaderService } from './shared/services/translation-loader.service';

/* Import language files in each module/component as needed */
import { locale as english } from './app.en';
import { locale as spanish } from './app.es';

@NgMoudule({
  ...,
  /* use forRoot() in the main app module only */
  imports: [TranslateModule.forRoot(), ...],
  ...
});
export class AppModule {
  constructor(
    private translate: TranslateService,
    private translationLoader: TranslationLoaderService
  ) {
    /* Config translation in root module */
    this.translate.addLangs(['en', 'es']);
    this.translate.setDefaultLang('en');
    this.translate.use('en');
    /* Load translations in each module/component as needed */
    this.translationLoader.loadTranslations(english, spanish);
  }
}

…and set up translation in each feature module/component as necessary…

/app/feature-module/feature.module.ts

...
import { TranslateModule } from '@ngx-translate/core';
import { TranslationLoaderService } from '../shared/services/translation-loader.service';

import { locale as english } from './feature.module.en';
import { locale as spanish } from './feature.module.es';

@NgModule({
  imports: [TranslateModule, ...],
  ...
})
export class FeatureModule {

  constructor(
    private translationLoader: TranslationLoaderService
  ) {
    this.translationLoader.loadTranslations(english, spanish);
  }

}

…and finally, in a component…

<h1 translate>app.title</h1>

I’m sure this solution isn’t perfect, but it works for us. If you come up with improvements I’d love to hear them! Something to watch out for. You can’t rely on translations from lazy loaded sibling or child modules to be present so make sure any translations needed across lazy loaded modules are available to a parent of those modules. Hope that helps!

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to load separate translation files per module and ... - GitHub
We want to load translation in per module as well as per component wise. My environment is : Angular CLI: 6.0.8. Node: 8.10.0...
Read more >
How to split your i18n file per lazy loaded module ... - Medium
Use Http 2 · Use sw-precache from Google to generate a manifest file · Use Idle-Preload as lazy loading strategy · Use server...
Read more >
ngx-translate: Separate translation file for module does not load
In the newly created module I have created an effect that will set the language in the translation service for the sub-module:
Read more >
Lazy translations loading from Angular | ISPsystem
As the name of the article suggests: cut the translations into chunks, spread them into different files and download them as needed. This ......
Read more >
How to translate your Angular app with ngx-translate
1. Add ngx-translate to your Angular application 2. Set up the TranslateService in your app.module.ts 3. Create your main language translation file (in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found