Using the TranslateService in Angular to externalize an array of strings

I am new to externalizing code. As I was working on developing a month picker in Angular, I initially had an array of months with hardcoded names in my typescript file:

arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

Upon the advice of a senior developer, I was recommended to externalize these names in a separate JSON file for easy modification in the future. Let me walk you through my updated code.

monthpicker.component.ts

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
    ...
})
export class MonthpickerComponent implements OnInit {

    constructor(private translate: TranslateService){
    }


    //arr = ['Jan', 'Feb', ... 'Nov', 'Dec'];
    monthArray = []; /* USING A DIFFERENT EMPTY ARRAY INSTEAD*/

    translateCard(): void {
        this.translate
            .get([
                'Months.January',
                'Months.February',
                ...
                'Months.December'
            ])
            .subscribe(translations => {
                this.monthArray.push(translations['Months.January']);
                this.monthArray.push(translations['Months.February']);
                ...
                this.monthArray.push(translations['Months.December']);
            });
            console.log(this.monthArray);
    }

    ngOnInit(): void {
        this.translateCard();
    }

   /* CODE TO READ MONTH NAMES AND RENDER IN HTML*/
    n = 4;
    matrix: any = Array.from({ length: Math.ceil(this.monthArray.length / this.n) }, (_, i) => i).map(i =>
        this.monthArray.slice(i * this.n, i * this.n + this.n).map(x => ({
            monthName: x,
            isSelected: false
        }))
    );

   ...
}

monthpicker.component.html

<div *ngFor="let row of matrix" class="my-table">
  <span *ngFor="let x of row">
    <span class="month-name">
      {{ x.monthName }}
    </span>
  </span>
</div>

Lastly, here is the content of en-US.json

{
  "Months": {
    "January": "Jan",
    "February": "Feb",
    ...
    "October": "Oct",
    "November": "Nov",
    "December": "Dec"
  }
}

After running the code, I did not encounter any errors or warnings in the console. Surprisingly, console.log(this.monthArray[]) also displays all the months correctly. However, the month-picker panel on the front-end appears blank. It seems there is an issue with the asynchronous call:

ngOnInit(): void {
  this.translateCard();
}

Despite trying various solutions, including utilizing translate.instant(), the panel still remains blank. I am unsure where I have gone wrong in my implementation. Any guidance would be greatly appreciated.

Answer №1

Once the subscription is complete, it is essential to fill the matrix array as the monthArray is populated asynchronously. Implement the following modification:

translateCard(): void {
    this.translate
        .get([
            'Months.January',
            'Months.February',
            ...
            'Months.December'
        ])
        .subscribe(translations => {
            this.monthArray.push(translations['Months.January']);
            this.monthArray.push(translations['Months.February']);
            ...
            this.monthArray.push(translations['Months.December']);
            // begin populating matrix
            this.matrix = Array.from({ length: Math.ceil(this.monthArray.length / 
                this.n) }, (_, i) => i).map(i =>
                    this.monthArray.slice(i * this.n, i * this.n + this.n).map(x => ({
                        monthName: x,
                        isSelected: false
                    }))
               );
        });

}

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

The combination of arrays and array methods in intersection types may encounter difficulty in accessing all fields

I have two different types, both in the form of arrays of objects with specified fields, combined into an intersection type in Typescript. When I access an element from the array, I can retrieve the second field without any issues. However, when I try to ...

When retrieving text using getString from a JSONObject in JSON format, it displays ''' instead of just '''

My limited knowledge in Java and Android has led me to believe that the issue may be related to encoding or decoding. Unfortunately, I have not been able to find any helpful solutions through online searches. When I use response.getString("key");, it incl ...

Errors in TypeScript are being brought up by using if-else statements inside a loop

I am currently working on a function to retrieve referral codes from users. The user inputs a code, which is then checked against the database to see if it exists or not If the code provided matches the current user's code, it should not be accept ...

Node Express application experiences issues with Handlebars rendering additional empty objects from JSON arrays

Currently, I am attempting to retrieve data from a REST API call and display it as a list using Handlebars, which functions as my view engine in a Node Express App. Below is the route I am using: router.get('api/projects', function(req, res){ ...

How can Material UI Textfield be configured to only accept a certain time format (hh:mm:ss)?

Looking for a way to customize my material ui textfield to allow input in the format of hh:mm:ss. I want to be able to adjust the numbers for hours, minutes, and seconds while keeping the colons automatic. Any suggestions would be welcomed. ...

Struggling with setting up Role-Based Access Control (RBAC) with cookie authentication in React

I've been working on incorporating Role Based Access Control into a React app using cookies, but I'm struggling to understand its use. The idea was to create a context that retrieves the data stored in the cookie through a specific API endpoint d ...

Enforcing uniform data types in nested objects in TypeScript

Currently, I am in need of generating a list of constants. For instance, const Days = { YESTERDAY: -1, TODAY: 0, TOMORROW: 1, } I am looking for a method to restrict the types of all properties within Days. In other words, if I attempt to add a pr ...

The utilization of .forRoot() in the feature modules hierarchy

Could someone please explain to me the best way to organize a hierarchy of nested feature modules with .forRoot() calls? For instance, let's say I have modules structured like this: - MainModule - SharedModule - FeatureModuleA - FeatureModuleA1 ...

The data type of the element is implicitly set to 'any' due to the fact that a 'string' expression cannot be used to reference the type '(controlName: string) => boolean'

checkError(typeofValidator: string, controlName: string): boolean { return this.CustomerModel.formCustomerGroup.contains[controlName].hasError(typeofValidator); } I am currently learning Angular. I came across the same code in a course video, but it i ...

What is the best way to update typings.json and typing files?

Here is the structure of my typings.json: { "globalDependencies": { "aws-sdk": "registry:dt/aws-sdk#0.0.0+20160606153210" }, "dependencies": { "lodash": "registry:npm/lodash#4.0.0+20160416211519" } } Currently, I find it tedious to update ...

Jackson: parsing an array of objects with varying types

Jackson: Converting Object Array to JSON and Back Causing Type Issues I have successfully converted an object array to JSON, but when I try to convert it back to an object array, some items lose their type. Specifically, objects like java.sql.Date are bei ...

I'm sorry, there seems to be a JSON error. The syntax is incorrect and it

I am facing a problem where I encounter an error when trying to post a JSON object. The error message reads: SyntaxError: JSON.parse: unexpected character Here is my JavaScript object: var $arr_data = { title: '', category: &apo ...

Checkbox in Struts2 not displayed in JSON when left unchecked

I have encountered an issue with my form - everything works perfectly except for one aspect. The problem lies with a checkbox, created using struts2 tags, which returns true when checked and does not appear in the JSON at all when left unchecked. <s:ch ...

Trying to organize JSON data by multiple parameters using jQuery

Regarding the topic discussed in this thread; I have successfully managed to sort an Array of JSON Objects by two fields. Additionally, the discussion mentions: "To include additional columns for sorting, simply add them to the array comparison." // ...

How can I pass additional props that are not specified in the interface while working with a React TS component?

I am working with a TS React component called MyButton.tsx: import React from 'react' interface MyButtonProps { children: JSX.Element | JSX.Element[], className?: string, variant?: 'big-button' | 'medium-button' | &apos ...

Error message: Typescript and Styled-Component conflict: GlobalStylesProps does not share any properties with type { theme?: DefaultTheme | undefined; }

I've encountered an issue while passing props inside GlobalStyles in the preview.js file of my storybook. The props successfully remove the background from the default theme, but I'm receiving an error from Typescript: The error message states " ...

No data returned in response despite successful execution of the code

As I attempt to execute the given python script for extracting data from Google Scholar, my code is producing an empty list as a JSON response. Despite having all required libraries installed, the issue persists. headers = { 'User-agent': &ap ...

Find the names of keys which have a value of true in reactjs

Greetings, I have a JSON file that contains information about different components. I am trying to extract only the Dashboard and Datatable sections where the "visible" attribute is set to true. { "MTs": { "Dashboard": { "id": 1, "visible ...

Utilizing ConfigurationBuilder to incorporate null values into a list using a json file

As I attempt to insert a list of enums into appsettings.json for later iteration in the code, I encounter an issue. When I include a null value in the list within the JSON file, it does not populate as a null value when loading the Settings from the file. ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...