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.
This is the right behavior. You can use localStorage (or other place) to store the selected language.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With