I have such a problem I use ngx-translate for translation. When I choose a language, it is saved in localStorage, but when I refresh the page, it disappears and returns me the keys that I wrote. And the same problem when you go to another page and update it will return the keys to me.
This is the header component code and I use there to save the selected language to localStorage and add languages.
constructor(public translate: TranslateService) {
translate.addLangs(['kz', 'ru']);
if (localStorage.getItem('locale')) {
const browserLang = localStorage.getItem('locale');
translate.use(browserLang.match(/kz|ru/) ? browserLang : 'kz');
} else {
localStorage.setItem('locale', 'kz');
translate.setDefaultLang('kz');}}
changeLang(language: string) {
localStorage.setItem('language', language);
this.translate.use(language);}
And this header.html where will I choose the language
<select #langSelect (change)="changeLang(langSelect.value)">
<option *ngFor="let lang of translate.getLangs()" [value]="lang"
[selected]="lang === translate.currentLang">{{ lang }}
</option>
</select>
Here is an example of how I use
<div >
<h1>{{ 'apply.tur1' | translate }}</h1>
<p>{{ 'apply.paragraph1' | translate }}</p>
<h1>{{ 'apply.date1' | translate }}</h1>
</div>
But there is such a moment that header.html it is used only on the main page, but not on the others. And when you update the main page, the translations will not disappear, but on another page, the translations disappear and gives me a key for translation
CodePudding user response:
Try adding the default language while importing the translate module in the module like below :
imports : [
...
TranslateModule.forChild({
defaultLanguage: localStorage.getItem('locale') || 'en',
}),
...
]
CodePudding user response:
Hopefully this is what you are looking, it checks if any key is found in the localStorage with the name locale
and if that is not the case, it will default to kz
as in your case:
<select #langSelect (change)="changeLang(langSelect.value)">
<option *ngFor="let lang of translate.getLangs()" [value]="lang"
[selected]="lang === translate.currentLang">{{ lang }}
</option>
</select>
constructor(public translate: TranslateService) {
translate.addLangs(['kz', 'ru']);
if (localStorage.getItem('locale')) {
translate.setDefaultLang(localStorage.getItem('locale'));
translate.use(localStorage.getItem('locale'));
} else {
translate.setDefaultLang('kz');
translate.use('kz');
localStorage.setItem('locale', 'kz');
}
}
changeLang(language: string) {
this.translate.use(language)
this.translate.setDefaultLang(language)
localStorage.setItem('locale', language)
}