Razvan.432
Razvan.432

Reputation: 663

Angular 2 translation change language in application

I am new to angular 2 and I am building my first app. I have problems understanding how to change the language globally, from a single place. Right now I can change the language in a Component. I am using a cookie to store selected language and is available globally via a service. From what I understand I think I have to use a listener for this but don't know how to put it in practice or if this is the correct way. An example will be much appreciated.

Thanks

import {Component} from "@angular/core";
import {TranslateService} from "ng2-translate";
import {SettingsService} from "../settings.service";

@Component({
    selector: 'rn-header',
    templateUrl: './header.html',
    styleUrls: ['./header.scss']
})
export class HeaderComponent {

    constructor(private translate: TranslateService, private settings: SettingsService) {
        translate.setDefaultLang(settings.getLanguage());
        translate.use(settings.getLanguage());
    }

    changeLanguage(language) {
        console.log('Language changed to: '+language);
        this.settings.setLanguage(language);
        this.translate.use(language);

    }

}

and the service

import {Injectable} from "@angular/core";
import {CookieService} from "angular2-cookie/services/cookies.service";

@Injectable()
export class SettingsService {
    defaultLanguage: string = 'en';

    constructor(private _cookieService: CookieService) {

    }

    getLanguage() {
        if (this._cookieService.get('RN_LANGUAGE_PREFERENCE')) {
            return this._cookieService.get('RN_LANGUAGE_PREFERENCE');
        }

        return this.defaultLanguage;
    }

    setLanguage(language: string) {

        this._cookieService.put("RN_LANGUAGE_PREFERENCE", language);
    }

}

Upvotes: 3

Views: 8468

Answers (1)

Ravi Teja
Ravi Teja

Reputation: 192

The best way to change language globally is to use pipes and send the language parameter as an argument.

This would automatically change the Language across the components where the language pipe is utilized.

The following example can be used to supply multiple languages at a time and can be used to change Language dynamically with a single click

for example:

// **language.pipe.ts**

import { Pipe, PipeTransform, OnInit, OnChanges } from '@angular/core';
import { LanguageService } from '../services/language.service';

@Pipe({
    name: 'language'
})
export class LanguagePipe implements PipeTransform {

    constructor(
        public lang: LanguageService
    ) { }

    transform(value: string, args?: any): any {
        return this.lang.getLang(value);
    }
}
// **language.service.ts**

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class LanguageService {

    selectedLanguage = 'ch';
    segmentsNames: any = {};
    constantSegmentNames: any = {};
    language = {
        undefined: { 'en': '', 'ch': '' },
        null: { 'en': '', 'ch': '' },
        '': { 'en': '', 'ch': '' },
        'hello': { 'en': 'Hello', 'ch': '你好' },
        'world': { 'en': 'World', 'ch': '世界' }
    };

    constructor(private _http: HttpClient) { }

    getLang(value: string, args?: any): any {
        if (this.language[value]) {
            return this.language[value][this.selectedLanguage];
        }
        return value;
    }

    /**
     * @function that is used to toggle the selected language among 'en' and 'ch'
     */
    changeLanguage() {
        if (this.selectedLanguage === 'en') {
            this.selectedLanguage = 'ch';
        } else {
            this.selectedLanguage = 'en';
        }
    }
}

Now Import

Language Pipe at App Module Level for it to be available across the app or import it in the common module as you require

// **app.module.ts**
import { NgModule } from '@angular/core';
import { LanguagePipe } from '../pipes/language.pipe';
import { APP_INITIALIZER } from '@angular/core';
import { AppConfig } from '../config.service';

export function initializeApp(appConfig: AppConfig) {
  return () => appConfig.load();
}

@NgModule({
  imports: [],
  exports: [
    LanguagePipe,
  ],
  declarations: [
    LanguagePipe,
  ],
  providers: [
    AppConfig,
    {
      provide: APP_INITIALIZER,
      useFactory: initializeApp,
      deps: [AppConfig], multi: true
    }
  ]
})
export class AppModule { }

Use the language service at the component level where ever the translation is required

// **header.component.ts**
import { Component, OnInit } from '@angular/core';
import { UserService } from '../login/user.service';
import { Router } from '@angular/router';
import { LanguageService } from '../services/language.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

  toolName = 'test';
  currentUser: string;
  isLoginPage = true;
  constructor(
    public userService: UserService,
    private router: Router,
    public lang: LanguageService
  ) { }

  ngOnInit() {
  }
}

Use Language Pipe in HTML as

//**header.component.html**
<strong>{{'hello' | language:lang.selectedLanguage}}{{'world' | language:lang.selectedLanguage}}</strong>

Upvotes: 2

Related Questions