Tips for implementing this feature in Angular to translate an object into multiple languages

When I previously used this service in another question:

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 currently utilizing this service in home.component.ts but struggling to determine the currently selected language.

In home.component.html, the following code is present:

<ul class="navbar-nav  navbar-right">
                <span class="form-inline">
                    <select 
                        class="form-control" 
                        #selectedLang 
                        (change)="switchLang(selectedLang.value)">
                      <option *ngFor="let language of translate.getLangs()" 
                        [value]="language"
                        [selected]="language === translate.currentLang">
                        {{ language }}
                      </option>
                    </select>
                  </span>        

            </ul>

How can the home.component.ts file know which language is currently being used through the service?

I am employing the ngx translation library.

 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"
}

Currently, there are no issues with translating static text, but the challenge lies in translating the room object. The library documentation does not provide any information on how to translate objects.

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

Answer №1

When working with the TranslateService, you'll find a handy property called currentLang which lets you know the currently selected language. Additionally, there's an event emitter named onLangChange that notifies you when the language changes. For more information on how to utilize the TranslateService, make sure to check out the details in the readme file on the official GitHub page.

Answer №2

One common scenario involves storing the language variable in localStorage or sessionStorage to ensure that user preferences remain even after a page refresh. It would be confusing for users if suddenly everything on the page switched to a different language.

To facilitate translations, we create i18n files in JSON format where key-value pairs are defined. Each language has its own file, and a translation service (such as Ngx Translate) is set up to handle the conversion of these pairs.

For instance, we might define a pair like this:

"HOME.TITLE" : "Bonjour Angular"
.

The key part (HOME.TITLE) is then integrated into the HTML template using the

{{("HOME.TITLE" | translate)}}
syntax. The TranslateService replaces the key with the appropriate value based on the selected language, displaying only Bonjour Angular to the user.

We also provide an example in a French language JSON file:

{
  "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');
  }
}

View a live demo here: https://stackblitz.com/edit/angular-translate-demo-7kfybu?file=src%2Fapp%2Fapp.component.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Different ways to handle dialogs in React with TypeScript

I'm currently working on developing a modal component in React TypeScript and I'm facing some issues in determining the correct type for a reference of an HTML dialog element. import { useRef } from 'react' const MyModal: React.FC = () ...

The attribute 'category' is not recognized on this particular object

While attempting to display a form on Next.js using Formik & typescript, I encountered the following error message: Property 'category' does not exist on type 'IntrinsicAttributes & object & { children?: ReactNode } Here is the code that tr ...

Trouble encountered with uploading files using Multer

I am facing an issue with uploading images on a website that is built using React. The problem seems to be related to the backend Node.js code. Code: const multer = require("multer"); // Check if the directory exists, if not, create it const di ...

When you extend the BaseRequestOptions, the injected dependency becomes unspecified

Implementing a custom feature, I have chosen to extend BaseRequestOptions in Angular2 to incorporate headers for every request. Additionally, I have introduced a Config class that offers key/value pairs specific to the domain, which must be injected into m ...

Typescript: Displaying two values as input (one being disregarded)

Is there a way to display both the name and id values in an input box that is set to readonly? <input readonly type="text" [value]="car.name"> I need to also show the car id. Any suggestions on how to achieve this? ...

Is it possible for TypeScript to verify key-value pair validity during compile time?

In my quest to efficiently cross reference field IDs with field definitions and validate them, I have encountered a common issue where string mismatches occur easily. Is there a method to establish a secure 1:1 mapping between dictionary types and their ke ...

Error in Typescript: TypeError is not defined

I am still getting the hang of TypeScript and React. Lately, I've been working on integrating the react-rewards npm library into my project but I'm facing one unresolved issue. type Props = {} class Surprisebutton extends Component<Props> ...

Employ ion-grid for a layout reminiscent of Duolingo's design

I am exploring the idea of creating a layout similar to Duolingo's interface. I have an array that specifies which buttons should be displayed, and I want them to be organized in pairs, with any odd element centered within the layout. However, I am s ...

Modify the class of the focused element exclusively in Angular 2

I'm working on a project that involves several buttons and div elements. Currently, the divs are hidden, but I want to be able to reveal a specific div when its corresponding button is clicked. For example: If you click the first button, only the fir ...

Error encountered in Angular8 Template Driven Form: TypeError - Attempt to access property 'ProviderName' of undefined resulting in Object.eval throwing an error in updateDirectives

An error has occurred with the template causing an issue. ProviderComponent.html:4 ERROR TypeError: Cannot read property 'ProviderName' of undefined at Object.eval [as updateDirectives] (ProviderComponent.html:4) at... provider.compo ...

Tips for providing a single store type to a component in the case of a union type store

Currently, I am utilizing Typescript in combination with React/Redux. When a visitor accesses the site, they can exist in one of two states: LoggedIn or LoggedOut. The structure of my state reflects this distinction: interface LoggedIn { token: strin ...

Acquire information from an Angular service and output it to the console

I am having trouble logging data from my service file in the app.component file. It keeps showing up as undefined. Below is the code snippet: service.ts getBillingCycles() { return this.http.get('../../assets/download_1.json'); }; app.com ...

Is it possible to utilize a template literal with a variable as an object key?

I tried to run the following code snippet but encountered an unexpected error: interface Person { firstName: string } const property: 'Name' = 'Name' const zack: Person = { [`first${property}`]: 'Zack' } An error is th ...

Create an object type with string keys and corresponding value types by combining a tuple type of string constants and another tuple type of different types

Contemplating how to define types for a concept similar to daggy, where a list of property names in an array leads to the creation of constructors. Thinking of something along these lines: [A, B] with [X, Y] => { [A]: X, [B]: Y } In this scenario, A ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...

ngx-datatables in Angular is experiencing issues with its filtering options

Having trouble implementing a filter option in ngx-datatables for all columns. I've written the code but it's not functioning correctly. Can anyone help me identify where I went wrong and find solutions? app.component.html: <label> Nam ...

Tips for resolving the ExtPay TypeError when using Typscript and Webpack Bundle

I am currently trying to install ExtPay, a payment library for Chrome Extension, from the following link: https://github.com/Glench/ExtPay. I followed the instructions up until step 3 which involved adding ExtPay to background.js. However, I encountered an ...

Incorporate CoreUI icons into a Vue.js TypeScript application

Currently, I am developing a Vue.js application using CoreUI in TypeScript. The issue I am facing pertains to CoreUI's icons. While my application runs smoothly and displays the icons, Visual Studio Code raises a concern about the specific line: icon ...

What is the process to switch the div's contenteditable attribute value from "false" to "true"?

I am currently experimenting with angular2 and I have a need to alter the value of a div- I want to change all contenteditable="false" to contenteditable="true" on my HTML page. Note that at times the contenteditable="false" attribute may be added to a ...

Steps for transforming a complex nested object into an observable and extracting specific values

First of all, I'm wondering if this is the recommended approach in Angular. Can I achieve this?: I have a JSON object with multiple levels of children and I need to console.log specific subsubsubsubchildren. Here is the code I tried: const observable1 ...