Utilize ngx-translate with an array as interpolation values

When working with ngx-translate, I use the instant method to translate messages into the user's language. These messages are provided as JSON objects and some of them contain dynamic values:

{
"message.key": "First value is {{0}} and second value is {{1}}",
"message.key2": "Value is {{0}}" 
}

To retrieve the translated text along with the interpolated dynamic values, I make use of the instant method in the following manner:

messageText = this.translateService.instant('message.key2', {0: 'Value to be interpolated'});

The issue arises when these values are returned in a string array params: string[]. In order to convert this string array into an Object format similar to {0:params[0], 1:params[1]}, I typically employ a conditional check as shown below:

myTranslationMethod(messageKey: string, params: string[]): string {
  let paramsAsObject;
  if (params.length === 1) {
    paramsAsObject = {
      0: params[0]  
    }
  } else {
    paramsAsObject = {
      0: params[0],
      1: params[1]
    }
  }
  messageText = this.translateService.instant(messageKey,paramsAsObject);
  return messageText; 
}

However, this approach necessitates updating the code each time a message with additional parameters is introduced. Is there a more generic solution that can handle any number of parameters without requiring manual adjustments?

I'm curious if it's possible to create paramsAsObject dynamically based on the length of params or directly utilize the array with ngx-translate. Any insights would be greatly appreciated.

Answer №1

It seems like you are looking to have the object paramsAsObject automatically created when params[] is provided.

translateMessage('', ['1', 'test', 'something']);

function translateMessage(key, params) {
  let paramsAsObject = {};
  for (let i = 0; i < params.length; i++) {
    Object.assign(paramsAsObject, {
      [i]: params[i]
    });
  }
  console.log(paramsAsObject);
}

// {0: "1", 1: "test", 2: "something"}

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

Encountered an issue finding element with Protractor - Error: script timed out after 20 seconds without receiving a response

I recently created a basic website using Angular 6 and I am facing some challenges while writing e2e tests for it. The first script is causing a lot of trouble for me as it throws the following error: C:\Users\user\Documents\workspace- ...

Is there a way to incorporate timeouts when waiting for a response in Axios using Typescript?

Can someone assist me in adjusting my approach to waiting for an axios response? I'm currently sending a request to a WebService and need to wait for the response before capturing the return and calling another method. I attempted to utilize async/aw ...

I'm diving into the world of Angular and Node.js and looking to transform XML into JSON. I'm torn between using the xmltojson and xml2json npm packages

I'm curious about a couple of things: 1. Why are there two different options for the same thing? 2. How do we decide which one to choose, and what criteria should we use? My application is built using Ionic 2, Angular, and Android. Can you please ...

What is the reason for the lack of compatibility between the TypeScript compilerOptions settings 'noEmitOnError: true' and 'isolatedModules: false'?

Whenever I try to execute TypeScript with isolatedModules set as true and then false, I keep encountering this error message: tsconfig.json(5,9): error TS5053: Option 'noEmitOnError' cannot be specified with option 'isolatedModules'. ...

React error: The DatePickerProps generic type must have one type argument specified

Date Selection Component: import React from "react" import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { LocalizationProvider } from '@mui/lab'; import { DatePicker, DatePickerProps } from '@mui/lab'; cons ...

Tips for duplicating chosen documents utilizing AngularCLI in conjunction with WebPack for the production build

I am facing an issue with my Angular2 app when building it for production using Angular CLI and WebPack. In order to deploy the app to our production server (IIS), I need to copy certain files to the dist folder. Specifically, I require the web.config and ...

typeorm migration:generate - Oops! Could not access the file

When attempting to create a Type ORM migration file using the typeorm migration:generate InitialSetup -d ormconfig.ts command, I encountered an error: Error: Unable to open file: "C:\_work\template-db\ormconfig.ts". Cannot use impo ...

Issue encountered when attempting to assign `fontWeight` within `makeStyles` using `theme` in Typescript: Error message states that the property is not

Currently, within my NextJS project and utilizing MUI, I am attempting to define a fontWeight property using the theme settings in the makeStyles function. Oddly enough, this issue only arises when building inside a docker container, as building locally po ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

core.js:5873 - An issue occurred where the property 'filename' could not be read due to being undefined

My aim is to upload images to my Node.JS server and retrieve them from an Angular client using the provided code snippets: image.ts: export class Image { fieldname: string; originalname: string; encoding: string; mimetype: string; des ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...

What types should be used when passing a NgRx Action as a parameter to a function?

Within my Effects function, I have implemented the following code structure. I have included a few lines of code for the catchError block to ensure that: Any errors are handled by the state/store The errors are forwarded to the global error handler / Int ...

Can a React function component be typed with TypeScript without the need for arrow functions?

Here is my current React component typed in a specific way: import React, { FunctionComponent } from "react"; const HelloWorld : FunctionComponent = () => { return ( <div> Hello </div> ); } export default HelloWorld; I ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

Instantiate the component array upon object instantiation

I'm currently in the process of learning Angular 2, so please bear with me if this question seems trivial. I am attempting to create a dynamic form that can be bound to a model. However, I am encountering an issue where I am unable to initialize my ar ...

Instructions for disabling editing for a specific cell within an inline editable row in primeNG

I am currently using PrimeNG DataTable with Angular, where the rows are editable as shown in the example in the documentation: https://www.primefaces.org/primeng/#/table/edit. However, I am facing an issue where I want to exclude one cell from being editab ...

Encountering build issues with Next.js on Vercel and local environments

As I work on my first Next.js website, I encountered a build error that persists both locally and on Vercel. Interestingly, I managed to achieve a successful local build at one point, but it no longer works. Here is an excerpt from my package.json: ...

Error: The OOP class value for translateX in the Web Animation API is returning as undefined

I'm currently working on a basic animation project using JavaScript. I have utilized the Animation class from the Web Animation API. My goal is to create multiple instances of this class in order to animate different elements with varying values and r ...

Using masonry-layout with Next Js leads to a ReferenceError stating that window is not defined

Implementing the masonry-layout library by David Desandro in my Next app has been a smooth process. You can find the link here. When I apply it, the masonry layout functions perfectly as intended. Here's how I'm incorporating it successfully: imp ...

Tips for transferring data between two pop-up windows in Angular2

My Angular2 project has a specific requirement that involves opening a first popup for users to enter some values. Upon a user event, like clicking a button, the first popup should close and a second popup should open with the values pre-populated from the ...