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
}
}
ng serve --configuration=de
– Krasnoyarsk