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

1

10

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
  }
}
Vitebsk answered 16/10, 2019 at 8:28 Comment(3)
what about traditiona way when you have baseHref='/ar/': angular.io/guide/i18n#build-for-multiple-localesRete
It is not suitable for you?Rete
I am trying to implement this in angular 8 but doesn't work. even in page refresh. only work if i run ng serve --configuration=deKrasnoyarsk
K
2

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();
  }
Kelsiekelso answered 16/10, 2019 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.