What is the best way to dynamically translate TypeScript components using transloco when the language is switched?

I am seeking clarification on how to utilize the TranslocoService in TypeScript. Imagine I have two lang JSON files for Spanish and Portuguese named es.json and pt.json. Now, suppose I have a component that displays different labels as shown in the following code snippet:

import { TranslocoService } from '@ngneat/transloco';
...

@Component({
  selector: 'app-powerbi',
  templateUrl: './powerbi.component.html',
  styleUrls: ['./powerbi.component.scss']
})

export class PowerbiComponent implements OnInit, OnDestroy {
...
contructor(
    private cdRef: ChangeDetectorRef, 
    private powerbiService: PowerbiService,
    private userservice: UserService, 
    private router: Router, 
    private loginservice: LoginService, 
    private store: Store<AppState>,
    private translocoService: TranslocoService
    )
    { 
      translocoService.setAvailableLangs([{ id: 'es', label: 'Spanish' }, {id: 'pt', label: 'Portuguese'}])
    }
...
 var diccionarioReports = [
              {
                titulo: this.translocoService.translateObject('powerbi.label1'),
                icono: 'grass',
                condicion: true
              },
              {
                titulo: this.translocoService.translateObject('powerbi.label2'),
                icono: 'water_drop',
                condicion: this.esCanha
              }
    ]
}

I have attempted to omit irrelevant code. It is worth mentioning that my current knowledge on this subject is limited. However, when changing languages, the labels do not switch their language dynamically like HTML pipes do with transloco. How can I achieve dynamic language changes for these 'labels' without needing to reload? If further information is necessary, please feel free to ask.

Answer ā„–1

translocoService includes a feature for language change subscriptions, allowing you to subscribe and update your labels accordingly when the language changes.

destroyed$ = new Subject<void>();

contructor(
    private cdRef: ChangeDetectorRef, 
    private powerbiService: PowerbiService,
    private userservice: UserService, 
    private router: Router, 
    private loginservice: LoginService, 
    private store: Store<AppState>,
    private translocoService: TranslocoService
    )
    { 
      translocoService.setAvailableLangs([{ id: 'es', label: 'Spanish' }, {id: 'pt', label: 'Portuguese'}])
    }
    
ngOnInit(): void {    
    this.translocoService.langChanges$.pipe(takeUntil(this.destroyed$)).subscribe((res) => {
        if (_.isEmpty(this.translocoService.getTranslation(res))) {
            this.subscription = this.translocoService.events$
                .pipe(
                    filter((e) => e.type === 'translationLoadSuccess'),
                    takeUntil(this.destroyed$),
                )
                .subscribe((obj) => {
                    // Perform action when translation is successfully loaded
                });
        } else {
            // Perform action when translation is available
        }
    });
}

ngOnDestroy() {
    this.destroyed$.next();
    this.destroyed$.complete();
}

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

React Component not displaying properly when used inside a map iteration

I am currently working on rendering multiple components using the .map method on an array with specific content. Although I can't find any errors in the console, the component is not appearing in the DOM as expected. I attempted to set subHeader to nu ...

Tips for troubleshooting an error in ionic when compiling a template

Hello, I'm currently working on my first app but encountered an error during the extraction process. ? Starter template: my-first-app āˆš Preparing directory .\testarashelia - done! > git.exe clone https://github.com/ionic-team/photo-gallery- ...

NextAuth is failing to create a session token for the Credential provider

Currently, I am in the process of developing an application using the t3 stack and am facing a challenge with implementing the credential provider from nextauth. Whenever I attempt to log a user in, I encounter an error in the console displaying the messag ...

Angular: Intercepting an HttpResponse to trigger additional calls before passing the response back to the caller

My current objective is to intercept a response and, if a certain value (CHALLENGE) is present, trigger a call to another API. I need to retry this process 3 times if necessary. Upon success, I should respond to the initial call and pass the result back to ...

Combining Angular, Node.js, and Spring Boot Java REST API to enable Angular Universal functionality

I am seeking guidance on integrating Angular with NodeJS and Spring Boot for my application. Currently, I have built a system that utilizes Angular for the frontend and Java/Spring Boot for the backend REST API. However, I have come across challenges with ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...

Definition file in TypeScript for an npm package provided by an external source - constructor

In my Node project, I am utilizing ES6 and Typescript. Despite this, there is a commonjs library that I need to incorporate. To address this, I have created my own .d.ts declaration file for the library: module "@alpacahq/alpaca-trade-api" { e ...

When setting up Webpack with TypeScript, an error is encountered related to imports

Recently, I attempted to convert my Webpack configuration from JavaScript to TypeScript but encountered numerous difficulties in the process. To kick things off, I created a basic webpack configuration file with some parts missing. Here is how my webpack.c ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

What could possibly prevent Jasmine Spyon from being named?

I am currently facing an issue with a failing test even though I have included the necessary calls. One specific area where I am encountering this problem is with the PrimeNG Message Service that I am spying on. Below, you can find the code snippet that I ...

Pressing the tab key while using Angular will halt any additional processes from running

I recently integrated a search bar into my Angular application. When I enter text in the input field, a customized dropdown menu appears below it. However, when I press the tab key, I expect the dropdown to close and for the focus to shift to the next inpu ...

Encountering a tslint issue: "Parsing error: Expression expected"

Could someone provide some insight on this issue? Iā€™m encountering an error message that says Failed to compile. Parsing error: Expression expected with this specific line of code - isLogViewVisible: dashboard?.logView !== null where the variable isLog ...

I'm having trouble figuring out how to access response headers with HttpClient in Angular 5. Can anyone

I recently developed an authentication service in Angular 5, where I utilize the HttpClient class to make a POST request to my backend server. The backend server then responds with a JWT bearer token. Here is a snippet of how my request looks: return thi ...

Leverage classes within components for effective dependency injection

Currently, I am working with Angular and have set up 1 component, 1 class, and 1 service in my project. The service is defined as an @Injectable class and properly configured in app.module.ts. @Injectable() export class MyService { My class receives the ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Issue with Firebase Functions trigger not activating

Just delving into the world of Firebase Functions for the first time using Typescript. I've written two functions: export const helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase!"); const testRe ...

Leverage a provider implementation within another implementation of the same provider in Angular

Is it possible to inject one provider implementation into another implementation of the same provider in Angular? I have been unable to achieve this so far. The goal is to be able to customize the second implementation using data from the first implementat ...

Information obtained from the visible is consistently indefinable

I provide a service that returns observables of an array of objects allItems: Item[] = [ { id: "1", name: "item 1" }, { id: "2", name: "item 2" }, { id: "3" ...

Avoiding redundant API requests in transclusion by ensuring that only one instance of the duplicated component is displayed

In my Angular project, I am utilizing transclusion to create a fixed view template with slots for dynamic content. The component I'm working with is called app-filter-details and here is its template: <div id="details-wrapper"> <div cla ...

Attempting to connect to "http://localhost:4242/webhook" was unsuccessful due to a connection refusal when trying to dial tcp 127.0.0.1:4242

In my next.js 13 project, I am integrating stripe with TypeScript and configuring the app router. To create a stripe event in my local machine, I ran stripe listen --forward-to localhost:4242/webhook, but now I am encountered with the error message stripe ...