In our Angular application, we have implemented functionality for two languages: German as the default and English as the alternative. This is made possible through the use of ngx-translate
within the translateService
.
A common issue occurs when users refresh the browser, causing the application to revert back to the default language.
To address this, the switchLang()
function is called from the 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 logic behind the switching of languages can be found in the component.ts file:
switchLang() {
this.languageService.switchLanguage();
}
Furthermore, there is a dedicated language service responsible for managing language settings:
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 translation functionality is powered by ngx-translate
.