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

Tips for efficiently inserting large amounts of data using a select subquery

I'm currently using Sequelize in my project and encountering difficulties in converting a simple query into Sequelize syntax. Furthermore, I am also exploring ways to efficiently perform bulk inserts for this particular query. The query in question i ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Changing the selection in the Angular Mat-Select dropdown causes the dropdown's position to shift

Issue with dropdown position: The dropdown should display below the select element, but when selecting the second value, it appears on top of the select element. I have removed any relevant CSS to troubleshoot, but the problem persists. See screenshots for ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Injecting Variables Into User-Defined Button

Presenting a custom button with the following code snippet: export default function CustomButton(isValid: any, email: any) { return ( <Button type="submit" disabled={!isValid || !email} style={{ ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

Having trouble with installing the angular-4-data-table-bootstrap-4 package in NG 4.4.6 environment

I am currently working on an NG 4 project and my package.json indicates that I am using angular 4.4.6. I am attempting to include the angular-4-data-table-bootstrap-4 package as outlined below, but I keep encountering the error mentioned here that I can&ap ...

Managing nested request bodies in NestJS for POST operations

A client submits the following data to a REST endpoint: { "name":"Harry potter", "address":{ "street":"ABC Street", "pincode":"123", "geo":{ &q ...

Angular: Custom Pipes Now Adding Currency Symbol to Model Values

I have encountered an issue involving two currency pipe examples. One example involves using the pipe directly in the view, while the other utilizes the pipe from the TypeScript code side. However, when attempting to submit form data, the value related to ...

The dynamic dropdowns in FormArray are experiencing issues with loading data correctly

Having trouble fetching data for selected country states using FormArray Index. The API keeps getting called every time the country code is passed to retrieve the data. Here's what I've tried, <form [formGroup]='formName'> ...

having trouble retrieving information from mongodb

Currently working with nestjs and trying to retrieve data from a collection based on the 'name' value. However, the output I am getting looks like this: https://i.stack.imgur.com/q5Vow.png Here is the service code: async findByName(name):Promi ...

The ng-bootstrap typeahead is encountering an error: TypeError - Object(...) is not functioning correctly

Hey there! I'm trying to integrate the Angular Bootstrap typeahead component in my Angular 5 application by following the linkToTypeahead. However, I'm encountering some errors along the way. Here's what I'm seeing: ERROR TypeError: Ob ...

The variable isJoi has been set to true but there is an error due to an unexpected

I am currently developing a NestJs backend on multiple machines. One of the machines is experiencing issues with the @hapi/joi package. When running the NestJs application in development mode on this specific machine, I encounter the following error: PS C ...

How to use Angular 7 to send a JSON object as a parameter in an HTTP GET

I am attempting to send a JSON structure to a REST service from Angular in this manner: let test5var = { "test5var1": { "test5var2": "0317", "test5var3": "9556" }, ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Having trouble launching simple ionic template: Issue with locating module 'fast-deep-equal'

Recently I started using Ionic and followed the steps to install the basic blank template as shown below. First, I installed Ionic and Cordova by running the command: npm install -g ionic Cordova. After that, I created my first Ionic project using the f ...

Error: Namespace declaration does not have a type annotation - TypeScript/Babel

After creating my app using the command npx create-react-app --typescript, I encountered an issue with generated code and namespaces causing Babel to throw an error. Here are the steps I took to try and resolve the issue: I ejected the project Updated b ...

The Angular dependency provider is failing to supply the requested alternative class

I am currently in the process of writing unit tests for the doc-manager.component component. This particular component relies on the DocService, but I want to swap it with instances of MockedDocService within my tests. By leveraging alternative class prov ...

Encountered an issue while trying to install the package '@angular/cli'

Encountered errors while attempting to install @angular/cli using npm install -g @angular/cli. The node and npm versions on my system are as follows: C:\WINDOWS\system32>node -v v 12.4.0 C:\WINDOWS\system32>npm -v 'C ...

Encountered a TypeError when using Angular 2 with ng-bootstrap and NgbTabset: Uncaught (in promise) error due to inability to read property 'templateRef'

I am attempting to use NgTabset but encountering an error that reads TypeError: Cannot read property 'templateRef' of undefined. Strangely, when I replace the ng-template with the template tag, everything works smoothly. Can anyone help me identi ...