Home > other >  how to use this service in angular to traslate the object into two languages
how to use this service in angular to traslate the object into two languages

Time:02-05

in other question I got this service

import { Injectable } from '@angular/core';

    import { BehaviorSubject, fromEvent, interval, merge, Observable } from 'rxjs';
    import { TranslateService } from '@ngx-translate/core'; 
    
    @Injectable({
      providedIn: 'root'
    })
    export class LanguageService {
    
      private _language: BehaviorSubject<string>;
      
      constructor (
        private readonly NgxTranslateService: TranslateService
      ) {
        this._language = new BehaviorSubject("en"); // Default language
        NgxTranslateService.use("en");
      }
    
      set languageSelected(value: string) {
        this._language.next(value);
        this.NgxTranslateService.use(value);
        console.log(this._language);
      }
    
      public getLanguage$(): Observable<string> {
        return this._language.asObservable();
        
      }
    
      public getCurrentLanguage(): string {
        return this._language.getValue();
      }
    }

I am using this service in home.component.ts but I dont know how to know which language it is currently selected.

in home.component.html I have

<ul >
                <span >
                    <select 
                         
                        #selectedLang 
                        (change)="switchLang(selectedLang.value)">
                      <option *ngFor="let language of translate.getLangs()" 
                        [value]="language"
                        [selected]="language === translate.currentLang">
                        {{ language }}
                      </option>
                    </select>
                  </span>        

            </ul>

how to know from home.component.ts which language it is used using the service?

I using ngx library traslante

 switchLang(language: string) {
    this.translate.use(language);
    this.translateEn = language === 'en';
   // this.translate.currentLang;
    console.log('current2' ,this.translate.currentLang);
    this.langGet(this.language);
  }

I have two .json files

en.json

{
    "NameContact": "Contact ",
    "Name": "Name",
    "Message": "Message",
    "Send": "Send",
    "PhoneNo": "Phone No",
    "Password": "Password",
    "Bio": "Enter bio",
    "TermsConditions": "I agree to terms and conditions.",
    "Submit": "Submit",
    "RoomType": "Room type",
    "Reference": "Reference",
    "Description": "Description"
}

right know I dont have problems to traslate static text but my problem is traslate the object room. I didnt find nothing in the library documentation for trasnlate the object.

 <div *ngIf="translateEn == true; then thenBlock4 else elseBlock4"></div>
                        <ng-template #thenBlock4>     <p >{{'RoomType' | translate}} {{ room.roomtype }}</p></ng-template>
                        <ng-template #elseBlock4> <p >{{'RoomType' | translate}} {{ room.roomtypeEs }}</p></ng-template>

CodePudding user response:

There should be a property on the TranslateService called currentLang. That tells you what language is currently selected. It even has an event emitter for when the language changes. That one is called onLangChange (maybe it is of help to you). You can take a look at the github page's readme file for more details about how to use the TranslateService.

CodePudding user response:

Typical use case would be to declare and set language variable somewhere in localStorage or sessionStorage - somewhere where user user choice wouldn't disappear on refresh, would be quite difficult to understand your page if suddenly everything was in another language.

We create i18n files (a JSON structured file) where we define key : variable. We create a new file for each language typically. We then set-up a service to handle translation of those key/value pairs for us (go to package would be Ngx Translate).

For example, we define a key/value pair: "HOME.TITLE" : "Bonjour Angular".

key part HOME.TITLE then gets added to html template {{("HOME.TITLE" | translate)}} and through the translate pipe we go to our TranslateService which will replace our key, with a value from currently selected language. Hence user will end up seeing only Bonjour Angular.

fr.json

{
  "HOME": {
    "TITLE": "Bonjour Angular",
    "SELECT": "Changer la langue"
  }
}
@Component({
  selector: 'app-root',
  template: `
    <div>
      <h2>{{ 'HOME.TITLE' | translate }}</h2>
      <label>
        {{ 'HOME.SELECT' | translate }}
        <select #langSelect (change)="translate.use(langSelect.value)">
          <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
        </select>
      </label>
    </div>
  `,
})
export class AppComponent {
  constructor(public translate: TranslateService) {
    translate.addLangs(['en', 'fr','zh-Hans']);
    translate.setDefaultLang('en');

    const browserLang = translate.getBrowserLang();
    translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
  }
}

Here is an example: https://stackblitz.com/edit/angular-translate-demo-7kfybu?file=src/app/app.component.ts

  •  Tags:  
  • Related