Angular 2 translation change language in application

后端 未结 1 1404
感情败类
感情败类 2020-12-01 17:59

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 lang

相关标签:
1条回答
  • 2020-12-01 18:16
    // 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 supple multiple language at a time and can be used to change Language dynamically on 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';
            }
        }
    }
    `
    
    // **Use Language Pipe in HTML AS**
    
    `<strong>{{'hello' | language:lang.selectedLanguage}}{{'world' | language:lang.selectedLanguage}}</strong>`
    

    PS: Don't forget to import the pipe & service in all the components where you want to use this functionality

    0 讨论(0)
提交回复
热议问题