angular 5 change locale dynamically for i18n

北战南征 提交于 2020-01-03 08:42:15

问题


I am trying to change locale dynamically to change i18n language. I have two files, the one with english values and the other one with french values.

What I've tried for now is something like that :

 ngOnInit() {
    const localeName = localStorage.getItem('locale') || 'fr';
    import(`@angular/common/locales/${localeName}.js`).then(locale => {
      registerLocaleData(locale.default);
    });
  }

but it gave me the following error :

error TS1323: Dynamic import cannot be used when targeting ECMAScript 2015 modules.

Any ideas on how I can switch from english to french dynamically? :/


回答1:


Well, not sure it's a good solution but here's what i've done. It works for my purpose so maybe it can help someone else.

in main.ts :

if (localStorage.getItem('locale') === null) {
localStorage.setItem('locale', 'en');
}

const locale = localStorage.getItem('locale');
declare const require;
const translations = require(`raw-loader!./locale/messages.${locale}.xlf`);

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    {provide: TRANSLATIONS, useValue: translations},
    {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'}
  ]
});

in html code :

<a  mat-menu-item href="" (click)="changeLang('fr')">
    <mat-icon>settings</mat-icon>
    <span>FR</span>
  </a>

  <a  mat-menu-item href="" (click)="changeLang('en')">
    <mat-icon>settings</mat-icon>
    <span>EN</span>
  </a>

in component.ts :

changeLang(lang: string) {

    if (lang === 'fr') {
      localStorage.setItem('locale', 'fr');
    }

    if (lang === 'en') {
      localStorage.setItem('locale', 'en');
    }
  }

don't yell at me, i'm just a newbie with angular ^^



来源:https://stackoverflow.com/questions/51704797/angular-5-change-locale-dynamically-for-i18n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!