Search code examples
angularionic-frameworkionic3multilingual

Multi language support without plugin in ionic app


Following is my constant file in which I am setting language of ionic app.

@Injectable()
export class Constant {
  public static selectedLang :string = 'EN';

  static setLanguage(languageCode : string){
    Constant.selectedLang = languageCode;

  }
  readonly data: any = {
    "EN": {
      //declared English variables used to be all over the application
             FORGOT_PASSWORD : "Forgot Password",
          }
    "MR": {
             //marathi variables
             FORGOT_PASSWORD : "पासवर्ड विसरलात",
           }
    "HI":{
             //Hindi variables
             FORGOT_PASSWORD : "पासवर्ड भूल गए",
         }
   LANG: any = this.data[Constant.selectedLang];
 }

I use this variables in HTML in following way:

<div>
   <h2>{{CON.LANG.FORGOT_PASSWORD}}</h2>
   <p>{{CON.LANG.FORGOT_PASSWORD}}</p>
</div>

ts file where I set language:

import {Constant} from "../../../../constants";
class ForgotPassword {
    constructor(public CON: Constant){}

    setLanguage(languageCode : string){
       Constant.setLanguage(languageCode);
    }
 }

Here, I want to keep English as my default language. When user explicitly changes the language by calling the function, then only language should be changed. But the issue is Even if user calls the function to change language, its not changed. App is always showing English variables.

Your help is appreciated.


Solution

  • I have got what I was doing wrong earlier. I made 'data' and 'LANG' variables of Constant file normal instead of static. And changed the setLanguage function as follows.

     setLanguage(languageCode : string){
        this.selectedLang = languageCode;
        this.LANG = this.data[this.selectedLang]; //line added
      }
    

    Also, I stored my selectedLanguage variable from component to session storage so that, language will not be changed after I close and open the app again.

     setLanguage(languageCode : string){
        this.CON.setLanguage(languageCode);
        this.sessionProvider.setLanguage(languageCode);
      }