Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly.

Here's what I have attempted so far:

ngOnInit() {

    this.customTranslateService.get("mainLayout.userProfileDropdown.changeLocale").subscribe((result) => {
      this.changeLocaleText = result;
    })

    this.customTranslateService.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
      this.changeLocaleText = this.customTranslateService.instant("mainLayout.userProfileDropdown.changeLocale");
    });

    this.userProfileMenuOptions = [
      {
        text: this.changeLocaleText, itemId: "LocaleSelect"
      },
      {
        text: "Report a bug", itemId: "BugReport"
      },
      {
        text: "Request a feature", itemId: "FeatureRequest"
      },
      {
        text: "Log Out", itemId: "LogOut"
      }
    ];

  }

customTranslateService is a service that wraps TranslateService.

The initial subscription is working properly, however, when switching languages, the onLangChange event triggers and changes the variable content correctly. But the reference to changeLocaleText in userProfileMenuOptions is not updated because it is not bound.

Using a BehaviorSubject may not be suitable here since this is TypeScript code, not HTML markup that can utilize the async pipe.

One potential solution could be recreating the userProfileMenuOptions array every time the language change subscription is called, although it may not be optimal for the component using the array.

PS: The use of instant works here due to an application loader loading all available languages before the user accesses the application.

Do you have any ideas on how to address this issue?

Answer №1

init() {

    this.customTranslationService.retrieve("mainLayout.userProfileDropdown.changeLanguage").subscribe((response) => {
      this.changeLanguageText = response;
    })

    const getUserPorfileMenuOptions = (changeLanguageText: string) => {
      return [
        {
          text: this.changeLanguageText, itemId: "LanguageSelect"
        },
        {
          text: "Report an issue", itemId: "IssueReport"
        },
        {
          text: "Request a new feature", itemId: "FeatureRequest"
        },
        {
          text: "Sign Out", itemId: "Logout"
        }
      ];
    }

    this.customTranslationService.translationService.onLangChange.subscribe((event: LangChangeEvent) => {
      this.changeLanguageText = this.customTranslationService.instant("mainLayout.userProfileDropdown.changeLanguage");
      this.userProfileMenuOptions = getUserPorfileMenuOptions(this.changeLanguageText);
    });

    this.userProfileMenuOptions = getUserPorfileMenuOptions(this.changeLanguageText);

  }

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

What is causing this issue? Error: [$compile:nonassign] The expression 'undefined' cannot be assigned! AngularJS 1.5

I'm currently working on developing a component to post "Tweets" on my personal website. However, I am facing an issue where I cannot input any text into the textarea. Below is an image showcasing the error: Please review my code in the file "editor ...

What is the best way to animate various sprites using distinct buttons in HTML and CSS?

I've been experimenting with animating a sprite by using different onClick button triggers. I encountered an issue where only one of the buttons works correctly in the fiddle. However, in my local file version, the other buttons work but only once and ...

Securing important code sections in Node/Express using Typescript: A guide

I'm fairly new to the world of JavaScript/Typescript/Node/Express, and as I've been researching, it seems there isn't a universally accepted method for locking critical sections of code in a Node/Express application. I've come across a ...

What is the best way to align content in the left center of a Paper component and ensure it stays that way on smaller devices?

Recently, I've been developing a component for my Goal Sharing social media platform. Here's what I have accomplished so far: https://i.stack.imgur.com/UDRim.png In an attempt to position the Avatar component along with two typography component ...

What is the best way to transfer user input as a key value or variable from an HTML form to an Express.js application and then

Is it possible to dynamically pass user input as the key value? For example, instead of /hand-hold?handhold=userinput, I want the value entered by the user each time to be used. Any assistance on this matter would be greatly appreciated. app.component.ts ...

Add flexible templates into List element in Ionic version 3

My Progress Being a newcomer to ionic, I successfully created a List component in ionic 3 that retrieves JSON data from the server and displays it as a list layout on specified pages using a list selector. Objective I am looking to showcase various list ...

Display or conceal a field depending on the user's input

I need to display a checkbox only when the firstname matches abc or if the email is [email protected]. var x = abc; //will be dynamic var y = abc @gmail.com jQuery("#firstname").on('change', (function(avalue) { return function(e) { ...

Implementing the Authorize tag in the HomeController of an ASP.NET Core Angular application with the Angular Single Page Application template, incorporating IdentityServer4

After utilizing the latest yeoman template for an ASP.NET Core Angular application, I integrated IdentityServer4 and created a client for the MVC application within it. // OpenID Connect implicit flow client (MVC) new Client { ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

Retrieve the file that has been uploaded to AWS S3

Here is a snippet of code to consider : var express = require('express'), aws = require('aws-sdk'), bodyParser = require('body-parser'), multer = require('multer'), multerS3 = req ...

Nextjs 13 brings exciting new features, one of which is the ability to call getStatic

I am working on a Next.js 13 application where I have organized my files in the 'app' directory instead of the usual 'pages'. All pages are statically generated during build time and data is fetched from an external API. Everything wor ...

Utilize the results of the "event's" output as a variable

Struggling with manipulating checkbox values? The `change` event on checkboxes might return an object like this: {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"} To transform the above object into a format that can be co ...

Is there a method to have JavaScript display all the information during a SQL while loop?

I'm currently working on implementing a timer for my script. However, I am facing an issue where the timer only counts down from the last result instead of each individual result returned from the query. Any assistance with resolving this problem woul ...

Using TypeORM to establish a ManyToOne relationship with UUID data type for the keys, rather than using integers

I am currently facing a challenge in my Typescript Nestjs project using TypeORM with a PostgreSQL database. The issue arises when trying to define many-to-one relationships, as TypeORM insists on creating an ID field of type integer, while I prefer using U ...

Previewing an uploaded image before submitting with FileBase64: A step-by-step guide

How can I implement a preview for an uploaded image before submitting the form? I have the upload functionality working but I would like to add a preview feature for the image. Below is the code snippet I am currently using: const [shop, setShop] = us ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

Determine the `overall` amount and adjust `overall` to equal `quantity * price` within a Typescript

I am looking to perform a calculation similar to this: total = quantity * price and continuously update the total when either the quantity or the price changes. template-output-snapshot app.component.html <form [formGroup]="editform" (ngSubm ...

Concealing Popover with internal click

I am currently implementing Vue-PopperJS in my project, following the setup provided on the linked page with a few modifications: <template> <Popper ref="popover" trigger="clickToToggle" :options="{ pla ...

Load styles in Nuxt asynchronously to improve performance

Is there a way to load styles asynchronously on the website or insert them in the footer? I am currently using Nuxt version 2.0.0 Here's what I have tried so far: Adding a plugin in webpack called async-stylesheet-webpack-plugin. However, this res ...

Delivering XML in response to a webmethod call

While working with an ajax PageMethod to call an asp.net webmethod, I encountered an issue when trying to pass a significant amount of XML back to a callback javascript function. Currently, I am converting the XML into a string and passing it in that form ...