Home > Enterprise >  How to pass and translate with the language selected option in other component using ngx-translate
How to pass and translate with the language selected option in other component using ngx-translate

Time:09-24

Using ngx-translate library for localization. It is working fine in the component where I am have placed. Scenario: I have created a component for select language dropdown and I am calling the component in Login component and using there. It's working fine. Now, I want to transfer the language selected to all other component after login.

I don't want to use select language option on each and every place. The language selected in Login page should reflect on other pages as well. How can I achieve this ? (I don't have other module as of now)

i18nService.ts :

currentLang = 'en';
  translateService: TranslateService;

  setSelectedLanguage(language:any) {
    this.currentLang = language;
    this.applyLanguage(this.currentLang);
  }
  private applyLanguage(language:any) {
    this.translateService.use(language);
  }
  getLanguages() {
    return this.translateService.getLangs();
  }

  constructor(translateService: TranslateService) {
    this.translateService = translateService;
  }

  setUpConf() {
    this.translateService.addLangs(['en', 'te', 'kn', 'hi']);
    this.translateService.setDefaultLang(this.currentLang);
    this.applyLanguage(this.currentLang);
  }

LanguageDropdown.ts

i18nConf: I18nConfigService;

  constructor(i18nConf: I18nConfigService) { 
    this.i18nConf = i18nConf;
    this.i18nConf.setUpConf();
  }

LanguageDropdown.html

<select class="form-input col-md-2" #langSelect
        (change)="i18nConf.setSelectedLanguage(langSelect.value)">
        <option *ngFor="let lang of i18nConf.getLanguages()" [value]="lang"
            [selected]="lang === this.i18nConf.currentLang">
            {{ lang }}</option>
</select>

CodePudding user response:

You can actually get the used language via the TranslateService. In the API you have the currentLang attribute which should give you the currently applied language: https://github.com/ngx-translate/core#properties

currentLang: The lang currently used

To use this in other components, you need to import the TranslateService of course.

To use you need to call it like this:

// This will contain the currently set language
const currentLang = this.translateService.currentLang; 

If you want to translate things, you have multiple ways. One way is the get method.

this.translateService.get('Message Not Found').subscribe(translation => {
  console.log(translation); // Here should be the translation
});

The other way (my preferred way) is to use the translate pipe:

<button mat-raised-button
        color="primary"
        (click)="confirm()">
  {{ 'Yes' | translate }}
</button>
  • Related