Patola
Patola

Reputation: 683

Change LOCALE_ID dynamically on angular

For example FB region setting supports 100s of Locales. How can we implement something like this on angular? does this mean we have to register all supported locales at development time?

enter image description here

Is there a way to change LOCALE_ID on angular without hardcoding setup work as follows and also dynamically change it. I am just after changing date time and number formats, language/text translation is not needed at the moment.

import localeFr from "@angular/common/locales/de"; registerLocaleData(localeFr, "de")

example https://stackblitz.com/edit/angular-dynamic-locale-ywninm?file=src%2Fapp%2Fapp.module.ts

Upvotes: 0

Views: 2792

Answers (2)

Subhash Labana
Subhash Labana

Reputation: 95

This solution work for me

        loadLocales(localeId){
          import(
            /* webpackExclude: /\.d\.ts$/ */
            /* webpackMode: "lazy-once" */
            /* webpackChunkName: "i18n-extra" */
            `@/../node_modules/@angular/common/locales/${localeId}`).then(module => {registerLocaleData(module.default)});
        
          }
    
    for calling function in component
    
    this.loadLocales('de') // fr
    
    // necessary import //
    import {registerLocaleData} from '@angular/common';
    import {  APP_INITIALIZER } from '@angular/core';
    
    
    //Add provider //
    
    providers: [
        {
          provide: APP_INITIALIZER,
          useFactory: TestFunc,
          multi: true,
          deps: [CommonService]
         }
    ]

culture= service.culture; //'de-DE'

// for template ref //

{{ showDateStart | date: "EEE, MMMM d, y, HH:mm": '' : culture}} //culture

if you define it for your application then you add it into app.module.ts

Upvotes: 0

Andrei
Andrei

Reputation: 12196

i am afraid default angular i18n is made in a way that you would be required to build angular app bundle for each locale. those /locales data will be auto imported by angular then. if it is not ok for you, use different i18n lib, the most popular one for angular is ngx-translate

Upvotes: 0

Related Questions