Is there a way to change the Locale_Id in my angular app during runtime without using window.location.reload()
to update the locale?
I need to implement a solution where I can switch locales dynamically without having to reload the entire application.
Below is the code snippet:
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
}
}