Angular4: Language for the user

I want to have LoginForm even after this user enters the application - either German or English. As far as I understand, I can set something like in app.module.ts

 import { LOCALE_ID } from '@angular/core'; providers: [{ provide: LOCALE_ID, useValue: 'de-DE' },...] 

But this is at startup, and not when LoginForm is already displayed: - / Is there a way to change the locale for the entire application? (Not just for a specific component!) - It would be great if translations could be changed also on the fly. What hints how to achieve? I just found a way to handle this.

+5
source share
3 answers

I followed the response of this thread , and I have the following solution:

 import { LOCALE_ID } from '@angular/core'; @NgModule({ // ... providers: [... {provide: LOCALE_ID, deps: [SettingsService], // some service handling global settings useFactory: getLanguage // returns locale string } ] // ... }) export class AppModule { } // the following function is required (for Angular 4.1.1!!!) export function getLanguage(settingsService: SettingsService) { return settingsService.getLanguage(); } 

Note: Using an additional function prevents the error Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function !!!!

and i create a class

 import { Injectable } from '@angular/core'; @Injectable() export class SettingsService { currentLang: string; constructor() { this.currentLang = 'en'; } setLanguage(lang: string) { this.currentLang = lang; } getLanguage() { return this.currentLang; } } 

which changes LOCALE_ID on the fly LOCALE_ID

+9
source

What you do in app.module.ts is the right way to do this for the whole application:

 @NgModule({ // ... providers: [ { provide: LOCALE_ID, useValue: 'de-DE'} ] // ... }) export class AppModule { } 

But, unfortunately, I do not think that this can be changed on the fly.

+1
source

How about this?

  • use local storage to store locale (e.g. 'fr')
  • load the associated translation file into main.ts (e.g. messages.fr.xlf)
  • set LOCALE_ID to app.module.ts

To change the locale

  • set a new locale in local storage
  • update application

main.ts

 declare const require; const locale = localStorage.getItem('locale'); const translation = require(`raw-loader!./locale/messages.${locale}.xlf`) platformBrowserDynamic().bootstrapModule(AppModule, { providers: [ {provide: TRANSLATIONS, useValue: translation}, {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'} ] }); 

app.module.ts

 @NgModule({ providers: [ {provide: LOCALE_ID, useValue: localStorage.getItem('locale')} ] }) export class AppModule { } 
0
source

All Articles