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.

i18n: document how to lazy load locale data on bootstrap of application

See original GitHub issue

I’m submitting a…


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Feature request
[x ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

Currently the documentation only states you should import the locale data you need for an app

Expected behavior

A typical enterprise app supports multiple cultures and may not know the culture until run time. An example of how to import the correct locale data at run time would be helpful.

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

This was discussed as part of #20193

Environment


Angular version: X.Y.Z


Browser:
- [ ] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Issue Analytics

  • State:open
  • Created 6 years ago
  • Reactions:3
  • Comments:39 (9 by maintainers)

github_iconTop GitHub Comments

19reactions
ocombecommented, Nov 17, 2017

This will work in a webpack project and generate the chunks for all of the locales automagically ! You might want to add some better locale to get the locale, this is just a crude version that uses the browser’s locale (which might not always be mapped to the locale files, which is why I only keep the first part of the locale, such as “fr” for “fr-FR”). In this case detecting the locale is synchronous, but you can change the order of the providers to use an async service with APP_INITIALIZER, don’t forget that it’ll delay the rendering of your app though…

import { NgModule, APP_INITIALIZER, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

declare var System;

export class LocaleService {
  getLocale(): string {
    if (typeof window === 'undefined' || typeof window.navigator === 'undefined') {
      return undefined;
    }

    let browserLang: any = window.navigator['languages'] ? window.navigator['languages'][0] : null;
    browserLang = browserLang || window.navigator.language || window.navigator['browserLanguage'] || window.navigator['userLanguage'];

    if (browserLang.indexOf('-') !== -1) {
      browserLang = browserLang.split('-')[0];
    }

    if (browserLang.indexOf('_') !== -1) {
      browserLang = browserLang.split('_')[0];
    }

    return browserLang;
  }
}

export function localeIdFactory(localeService: LocaleService) {
  return localeService.getLocale();
}

export function localeInitializer(localeId: string) {
  return (): Promise<any> => {
    return new Promise((resolve, reject) => {
      System.import(`@angular/common/locales/${localeId}.js`)
        .then(module => {
          registerLocaleData(module.default);
          resolve();
        }, reject);
    });
  };
}

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent],
  providers: [
    LocaleService,
    { provide: LOCALE_ID, useFactory: localeIdFactory, deps: [LocaleService] },
    {
      provide: APP_INITIALIZER,
      multi: true,
      useFactory: localeInitializer,
      deps: [LOCALE_ID]
    }
  ]
})
export class AppModule { }
4reactions
TomCasertacommented, Jul 5, 2018

@birnihigo You can tell webpack to exclude languages you don’t want using magic comments:

eg.

import(
   /* webpackInclude: /(de|en|ca|no|fi|sv|tr|en-GB)\.js$/ */
   `@angular/common/locales/${locale}.js`
).then((module) => {
    registerLocaleData(module.default);
});

You can also use the magic comment /* webpackExclude: /(languages|here)\.js$/ */ to exclude (if your list of excludes is smaller than your includes.

If you want a single locale though then just bundle it with your app with a normal import, or don’t use the patterned import eg:

import('@angular/common/locales/tr.js')// ...
Read more comments on GitHub >

github_iconTop Results From Across the Web

Lazy Loading Locales with Angular - ANGULARarchitects
One concept it contains is called global locales. These are bundles with meta data for different date and number formats the CLI can...
Read more >
Angular 5 i18n with JIT - Lazy Loading Language files
We're using Angular 5 with JIT and would like to replace the XLF content used for translations in the app, depending on a...
Read more >
Lazy Load and Encapsulate i18n Files in Angular with Transloco
In this case, Transloco will load the active language's file, and use it for the translations. Of course, As our application grows, our...
Read more >
Prefetch the User Language | Transloco Angular i18n
This will make sure the application doesn't bootstrap before Transloco loads the translation file based on the current user's language.
Read more >
A Guide to React Localization with i18next | Phrase
This can speed up our app when we have large translation files and/or when we have many of them. i18next provides a mechanism...
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