7

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? :/

2
  • Possible duplicate of Angular 2 i18n dynamic/instant translation Commented Aug 6, 2018 at 9:51
  • not sure if that a duplicate, but thanks for the link, i may have passed over this one. plus : the solution which is proposed in there does not work for me. it comples but doesn't do anything Commented Aug 6, 2018 at 10:12

2 Answers 2

7

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 ^^

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, just spent some hours on a similar problem and understanding the main differences between standard i18n and "hot" translation of the page, I think a better result can be achieved by using github.com/ngx-translate/core
0

Agree with @j0w and I want to say that it works fine on Angular 5.

Remember to include the corresponding imports as I forgot to do so...:

import { enableProdMode, TRANSLATIONS, TRANSLATIONS_FORMAT } from '@angular/core'; 

Remember, isn't a recommended way to translate your Angular site on modern Angular versions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.