Importing translation files into your application with the JiT Compiler

The JiT (Just-in-time) compiler compiles the application dynamically, as the application loads. To do this, we will need to rely on 3 providers that tell the JiT compiler how to translate the template texts for a particular language:

  • TRANSLATIONS is a string containing the content of the translation file.
  • TRANSLATIONS_FORMAT is the format of the file.
  • LOCALE_ID is the locale of the target language.
    Here's how to boostrap the app with the translation providers for French. We're assuming the translation file is messages.fr.xlf.

app/index.ts:

  1. import { NgModule, TRANSLATIONS, TRANSLATIONS_FORMAT, LOCALE_ID } from '@angular/core';
  2. import { BrowserModule } from '@angular/platform-browser';
  3. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  4. import { Hello } from './app.component.ts';
  5. // Using SystemJs' text plugin
  6. import translations from './messages.fr.xlf!text';
  7. const localeId = 'fr';
  8. @NgModule({
  9. imports: [
  10. BrowserModule
  11. ],
  12. declarations: [
  13. Hello
  14. ],
  15. bootstrap: [ Hello ]
  16. })
  17. export class AppModule {
  18. }
  19. platformBrowserDynamic().bootstrapModule(AppModule, {
  20. providers: [
  21. { provide: TRANSLATIONS, useValue: translations },
  22. { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
  23. { provide: LOCALE_ID, useValue: localeId }
  24. ]
  25. });

View Example

We're using SystemJS text plugin to import raw xlf files. We could alternately use webpack and raw-loader to achieve the same effect. Better yet, we could make an http call based on which language we're interested in, and asynchronously bootstrap the app once its loaded.

原文: https://angular-2-training-book.rangle.io/handout/i18n/import-using-jit.html