Issue
This seems like a relatively simple thing to do but I cannot seem to find any examples (Stackblitz, blogs, ngx-translate docs, etc.) of anyone doing it and cannot work it out myself.
I want to change the displayed value of my dropdown from "en", "es", "fr" to "English", "Espanol", "Francais". Changing the value in addLangs() seems to change the value in the dropdown but of course it cannot find en.json, etc.
component.html
<select class="form-control" selLang (change)="translateLanguageTo(selLang.value)">
<option *ngFor="let language of translate.getLangs()" [value]="language" [selected]="language === translate.currentLang">
{{ language }}
</option>
</select>
app.component.ts
this.translate.addLangs(['en', 'es', 'fr']);
Solution
As you noticed yourself, ngx-translate only cares about the language codes and not their names. You can work around this though.
Create a constant which contains all supported languages (language code + language name).
// supported-languages.ts
export const SUPPORTED_LANGUAGES = [
{ code: 'en', name: 'English' },
{ code: 'es', name: 'Espanol' },
{ code: 'fr', name: 'Francais' },
]
Import that constant into your component.
// language-selector.component.ts
import { SUPPORTED_LANGUAGES } from './path/to/supported-languages';
class LanguageSelectorComponent {
languages = SUPPORTED_LANGUAGES
// ... rest of the methods
}
Iterate over the supported languages and display their names.
<!-- my.component.html -->
<select class="form-control" (change)="translateLanguageTo($event)">
<option *ngFor="let language of languages" [value]="language.code" [selected]="language.code === translate.currentLang">
{{ language.name }}
</option>
</select>
And define the languages for ngx-translate in your app.component.ts as follows:
import { SUPPORTED_LANGUAGES } from './path/to/supported-languages';
...
this.translate.addLangs(SUPPORTED_LANGUAGES.map(l => l.code);
By using this strategy you can define all supported languages in one file and easily add/remove languages later without touching other parts.
Answered By - Tsvetan Ganev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.