I am building an application and it is 4 different languages for that I am using angular ng-translate. This is working fine but I have a small issue if I change language and refresh the page the website will go back to the default language. I want it to be in the selected language even on refresh until the user changes it. I know it is not a big issue, I have to store it somehow in local storage but I tried a lot and could not do it. Can anybody please help me with the code? I could not code this logic. I am very new to angular. Here is my app component
import { Component } from '@angular/core';
import {TranslateService} from "@ngx-translate/core";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Seeds';
constructor(public translate: TranslateService) {
translate.addLangs(['English', 'Español', 'Deutsch', 'Ελληνική']);
translate.setDefaultLang('English');
}
switchLanguage(lang: string) {
let language = (this.translate.use(lang))
localStorage.setItem('language', JSON.stringify(language))
}
}
Here is my app.component.html file
<div >
<span>Change Language</span>
<span >
<select
#selectedLang
(change)="switchLanguage(selectedLang.value)">
<option *ngFor="let language of translate.getLangs()"
[value]="language"
[selected]="language === translate.currentLang">
{{ language }}
</option>
</select>
</span>
</div>
CodePudding user response:
Try adding to your constructor :
constructor(public translate: TranslateService) {
translate.addLangs(['English', 'Español', 'Deutsch', 'Ελληνική']);
if(localStorage.getItem('language')){
this.translate.use(JSON.parse(localStorage.getItem('language')));
}else{
translate.setDefaultLang('English');
}
}
CodePudding user response:
The variable that you receive on switchLanguage()
is already a string, so, just store it, then when you go to get the item back from the localStorage create some sort of condition. Something like this:
localStorage.setItem('language', lang);
if (localStorage.getItem('language') == 'English') {
do something
}