ionic-frameworkionic2ng2-translate

Change language on Ionic2 - What is the most effective way to change all page language?


I am trying to use ng2-translate on Ionic2 to do the multi-language, and I added a button for changing the language of the Apps on the setting page. Basically, the function of changing language is work on the setting page only, but the other page will not happen anything.

And I have a stupid way to do the translation, that is add a function ,which change the language of the current page, on every pages and it will be executed when I click the button on the setting page.

But this solution less efficiency, how can do the same thing in a effective way?

Here is a part of my code:

  1. Setting Page:

      import { Component,  ViewChild } from '@angular/core';
    
      import { NavController, List } from 'ionic-angular';
      import {TranslateService, TranslatePipe, TranslateLoader, TranslateStaticLoader} from 'ng2-translate/ng2-translate';
      @Component({
          selector: 'page-setting',
          templateUrl: 'setting.html'
       })
    
      export class SettingPage {
          translate;
         @ViewChild(List) list: List;
         constructor(public navCtrl: NavController,   translate: TranslateService) {
              translate.setDefaultLang('zh');
              this.translate = translate;
          }
           //When the translation button is clicked
           click() {
              this.translate.use('en');
                   //Change all the pages language
                   location.change('en');`enter code here`
                   home.change('en');
             }
    
      }
    

Solution

  • i have the same, a settings page to change language.

    I have this on html:

    <ion-item>
      <ion-label class="primary-text-color">{{ 'Settings.settings.language' | translate }}</ion-label>
      <ion-select [(ngModel)]="language" (ionChange)="onChange($event)">
        <ion-option value="es">Español</ion-option>
        <ion-option value="en">English</ion-option>
      </ion-select>
    </ion-item>
    

    Then on my ts file:

    import { TranslateService } from 'ng2-translate';
    
    [...]
    
    language: String;
    
    constructor(public translate: TranslateService) {
        this.language = translate.currentLang;
        this.usermail = this.userdata.getEmail();
    }
    
    onChange(e) {
        this.translate.use(e);
    }
    

    This will change your language in all pages, just use the {{ 'Settings.info.mail' | translate }} pipe and it will change the translation when you pick another language with no more changes.

    Hope it helps you