Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change the locale in Angular 7 at runtime without having to reload the app

I am trying to change Locale_Id in my angular app at the runtime but must use window.location.reload() to fire changes at locale.

I want to change locale without reloading my app.

here is my code:

app.module

import { LOCALE_ID } from '@angular/core';
import { LocaleService} from "./services/locale.service";

@NgModule({
    imports: [//imports],
    providers: [
        {provide: LOCALE_ID,
         deps: [LocaleService],
         useFactory: (LocaleService: { locale: string; }) => LocaleService.locale
        }
    ]})

locale.service

import { Injectable } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeEnglish from '@angular/common/locales/en';
import localeArabic from '@angular/common/locales/ar';

@Injectable({ providedIn: 'root' })
export class LocaleService{

    private _locale: string;

    set locale(value: string) {
        this._locale = value;
    }
    get locale(): string {
        return this._locale || 'en';
    }

    registerCulture(culture: string) {
        if (!culture) {
            return;
        }
        this.locale = culture;

        switch (culture) {
            case 'en': {
                registerLocaleData(localeEnglish);
                break;
            }
            case 'ar': {
                registerLocaleData(localeArabic);
                break;
            }
        }
    }
}

app.component

import { Component } from '@angular/core';
import { LocaleService} from "./services/locale.service";

@Component({
  selector: 'app-root',
  template: `
    <p>Choose language:</p>
    <button (click)="english()">English</button>
    <button (click)="arabic()">Arabic</button>
  `
})
export class AppComponent {

  constructor(private session: LocaleService) {}

  english() {
    this.session.registerCulture('en');
    window.location.reload(); // <-- I don't want to use reload
  }

  arabic() {
    this.session.registerCulture('ar');
    window.location.reload(); // <-- I don't want to use reload
  }
}
like image 331
El7or Avatar asked Nov 06 '22 13:11

El7or


1 Answers

I think you don't need to reload, but just delay a little to ending registerCulture

for example:

english() {
    spinner.show();  // <-- start any loader
    setTimeout(() => {
            this.session.registerCulture('en');
            spinner.hide();  // <-- stop the loader
          }, 1000);    
    // window.location.reload();
  }
like image 119
zizo Avatar answered Nov 13 '22 19:11

zizo