Reputation: 997
We have an Angular application which has two languages. The default is German and the other one is English. We are using ngx-translate
as the translateService
.
When you refresh the browser, the application switches back to the default language.
The switchLang()
function gets called in our navigation bar:
<li class="nav-item">
<a class="nav-link" id="switchLang" (click)="switchLang()">
<span>
<i class="fa fa-globe" aria-hidden="true"></i>
<span>{{'switch-lang' | translate}}</span>
</span>
</a>
</li>
the component.ts:
switchLang() {
this.languageService.switchLanguage();
}
And the language service:
import { Injectable } from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
@Injectable({ providedIn: 'root' })
export class LanguageService {
private language = 'de';
constructor(private translateService: TranslateService) { }
getCurrentLanguage() {
return this.language;
}
getLocale() {
if (this.language === 'en') {
return 'en_US';
} else {
return 'de_DE';
}
}
switchLanguage() {
if (this.language === 'en') {
this.language = 'de';
} else {
this.language = 'en';
}
this.translateService.use(this.language);
}
}
The translateService
is the ngx-translate.
Upvotes: 5
Views: 8353
Reputation: 269
You can use localStorage to store the value in device memory, the following is an example
// function select language
selectLanguage(i: number) {
this.lag = this.languages[i];
this.translateService.use(this.languages[i].title.toLowerCase());
localStorage.setItem("language",this.languages[i].title.toLowerCase());
}
Upvotes: 2
Reputation: 2858
This is the right behavior. You can use localStorage (or other place) to store the selected language.
Upvotes: 7
Reputation: 1387
Angular service lives entirely in memory. If you want to add a persistence you should save current value to the localStorage on a language change or save this setting to the server
Upvotes: 0