Showing object data in TypeScript HTML when the object property starts with a numeral

Below is the function found in the TypeScript file that retrieves data from an API:

.ts file

getMachineConfigsByid(id) {
    this.machinesService.getMachineConfigById(id).subscribe((res) => {
      if (res.status === 'success') {
        this.configs = res.histories;
        let data = _.groupBy(this.configs, 'config_type');
        this.led = data.led;
      } else {
        this.toastr.error(res.message, 'Error !');
      }
    }, (err) => {
      console.log(err);
    });
  }

Example of how the data from the led array looks like:

[
   {
      "id":37,
      "machine_id":611,
      "config_type":"led",
      "description":{
         "24v_led":true,
         "12v_led":false,
         "5v_led":false
      },
      "update_type":null,
      "created_at":"2020-02-20T14:53:04.727+05:30",
      "updated_at":"2020-02-20T14:53:04.727+05:30"
   },
   ...
]

Now, to display this data stored in the led array in an HTML file with the following structure.

.html

<div *ngFor="let item of led">
    <div class="mb-4 section-header-configuration">
      <p class="mb-0"><b>LED Config</b>
        <span class="float-right">
          <p class="mb-0"><b>On : {{item?.created_at | date:'dd/MM/yyyy'}}</b></p>
        </span>
      </p>
    </div>
    <div>
      <div class="mb-3 col-12">
        <span class="mr-2 wdth-200">24 V LED:</span>
        <span class="status d-inline-block">
         {{item?.description?.24v_led ? 'Yes' : 'No' }}
        </span>
      </div>
    </div>
  </div>

However, it resulted in an error due to not being able to interpolate a string within an object starting with a digit:

core.js:7187 ERROR Error: Uncaught (in promise): Error: Template parse errors:
Parser Error: Unexpected token 24, expected identifier or keyword at column 20 in [ {{item?.description?.24v_led ? 'Yes' : 'No' }} ] in ng:///MachinesModule/MachineConfigDetailsComponent.html@36:48 ("       <span class="mr-2 wdth-200">24 V LED:</span>
            <span class="status d-inline-block">[ERROR ->]
              {{item?.description?.24v_led ? 'Yes' : 'No' }}
            </span>
          </div>
"): ng:///MachinesModule/MachineConfigDetailsComponent.html@36:48
...

Answer №1

To retrieve the properties of an object, you can treat it as a string index within an array-like structure. Using object['value'] is the same as using object.value. This technique is commonly known as bracket notation.

For example:

{{item?.description && item?.description['24v_led'] ? 'Yes' : 'No' }}

While TypeScript's optional chaining might not seamlessly integrate with this property access method, I found that it didn't work in my demonstration.

DEMO: https://stackblitz.com/edit/angular-cqkbmk

Update:

Although combining TypeScript's optional chaining with this approach should theoretically be possible, I encountered difficulties making it work in stackblitz. However, this doesn't necessarily mean it cannot be achieved.

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 the best way to search for specific data in a MongoDB database?

When using angular2 in conjunction with meteor, the data contains the following information: { "_id" : "DxEraKtfYavoukdCK", "name" : "Aaron", "capacity" : 20, "available_capacity" : 15, "location" : "1" } { "_id" : "yMhEggaGmS7iio9P4", "name" : "Benard ...

Typescript allows you to apply a filter to an array

Query: Is there a way to display a pre-selected item from my dropdown using its unique ID? Issue/Explanation: The dropdown options in my web service are dynamically fetched based on a user's ZipCode. For example, a Provider is displayed as {Pho ...

Assigning to a constrained type with an indexable signature results in failure

When using typescript 4.7.2, I encountered an issue where the following code fails only when assigning a value: type IndexableByString = { [k: string]: any }; function test<T extends IndexableByString>(target: T, key: string) { var prop = target ...

The current Angular 11 build seems to lack in producing sufficient Lazy chunk files

Currently, I am working on implementing lazy loading for modules from different libraries in my project. This involves utilizing two libraries located in the node_modules directory, which are then lazily loaded by the main application. Below is a snippet o ...

Modifying the value of an object key with Javascript

The information I am working with is structured as follows: obj = { pref: { language: 'English', } }; My goal is to update the language field to 'Spanish'. ...

Retrieving data from .NET API in Angular

I'm currently developing a project using Angular 7 and .NET Core. I’m facing an issue with passing file contents from a .NET API to Angular. Here's my API code: public async Task<IActionResult> GetLicenseInformation() { try { ...

How to create classes in typescript without utilizing the class keyword

As someone new to TypeScript, I have a curious question about classes. In pre-ES6 JavaScript, there were no classes. So, naturally, one would think it's possible to avoid using them in TypeScript as well. However, I am struggling to figure out the c ...

Integrating Typescript into function parameters

I am attempting to make my function flexible by allowing it to accept either a string or a custom type onPress: (value: string | CustomType)=>void But when I try to assign a string or CustomType, the compiler gives an error saying is not assignable to ...

Navigating the complexities of applying CSS exclusively to child grids within Kendo Angular may seem challenging at first

This image illustrates the grid layout I have created an angular UI using kendo that features a nested grid. I am trying to apply CSS specifically to the child grid without affecting the parent grid. However, no matter what CSS I write, it ends up being a ...

Learn how to bring a component into another component within Angular

I have developed a component named CopySchedulefromSiteComponent and now I am looking to import it into another component called SiteScheduleComponent. However, I am unsure of the correct way to do this. The CopySchedulefromSiteComponent contains one fiel ...

The installation of Node on Ubuntu 18.04 encountered an error

Could someone assist me with this problem? I initially had node installed, then uninstalled it using the rm -rf command following online suggestions. Now I am trying to reinstall it using nvm install node However, I'm encountering the following error ...

How can you display or list the props of a React component alongside its documentation on the same page using TypeDoc?

/** * Definition of properties for the Component */ export interface ComponentProps { /** * Name of something */ name: string, /** * Action that occurs when component is clicked */ onClick: () => void } /** * @category Componen ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

Attempting to incorporate NestJS modules into an NX monorepo is a task that Angular is currently

Recently, I encountered a frustrating issue while working with a monorepo that contains both Angular and NestJS. In an attempt to access DTOs, I made the mistake of including NestJS files on the client side. This caused Angular compilation errors due to de ...

Tips for tracking the evolution of changes to an array within React State

Experiencing challenges with saving the history of updates and modifications on a State. I have an object called "Journey" which includes a list of workshops (another array). Whenever I update my list of workshops, I aim to create a new array that captures ...

Issue with narrowing TypeScript arrays often encountered

When working with arrays of strings in my TypeScript code, I restrict the contents to certain letters by using a defined type like ("A" | "B")[] for letters such as A and B. However, when I have a function that takes an arbitrary array ...

What is the best way to combine two arrays and generate a new array that includes only unique values, similar to a Union

Here are two arrays that I have: X = [ { "id": "123a", "month": 5, "markCount": 75 }, { "id": "123b", "month": 6, "markCount": 85 ...

Expanding MaterialUi styled components by incorporating TableCellProps: A guide

When trying to create a styled TableCell component in a separate file, I encountered an error in TypeScript (ts(2322)). TypeScript was indicating that the properties "component," "scope," and "colSpan" could not be used because they do not exist in StyledC ...

Developing a constructor method that is conscious of data types

In my current scenario, I am dealing with a set of types: X, Y, and Z, all of which extend the same common interface J. My goal is to define a method that looks like this: class MyClass { private someNumber = 1; private someProperty; addEleme ...

Entering information into fluctuating object fields

Suppose I have a dynamic object with a union type: data: {[key in 'num' | 'str' | 'obj']: number | string | object}; I set the object properties as follows: data.num = 1; data.str = 'text'; data.obj = {}; E ...