Generate a dynamic key within a variable and set a corresponding value in typescript

Within my component, I have created a variable as an array called info[], with the intention of dynamically assigning values based on data from a service.

export class CostsComponent implements OnInit {

  public info: any[] = [];
  constructor(private deliverablesService: DeliverablesService, private setupcostsService: SetupcostsService, private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: Params) => {
      this.setupcostsService.getcostDetails(2940).subscribe(
        data => {
          this.info.col = data.col; // dynamic
          this.info.data = data.data; //dynamic
          console.log('cost Info',data);
        },
        () => { }
      );

    });
  }

When attempting to set this.info.col, it results in the error message '

Property 'col' does not exist on type 'any[]'
'.

Answer №1

When initializing a variable as an array, it's important to remember that you can't read an array property without using an index. To avoid issues, consider defining the variable as an object instead of an array.

Consider using public info: any = {}; instead of public info: any[] = [];

For more insight, check out this discussion:

Exploring the difference between 'any' and 'any[ ]'

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

A recent update to ngx-mask v16.2.6 has caused an issue where the module "ngx-mask" is unable to export the member "NgxMaskModule."

Following my upgrade to ngx-mask version 16.2.6, I have encountered an issue where the Angular compiler is unable to locate NgxMaskModule exported from 'ngx-mask'. The error message that I'm seeing reads as follows: ERROR in ./src/.....ts:2 ...

What is the best way to locate an item within a Redux array when working with TypeScript?

Below is the content of my slice.ts file. interface iItem { Category: string; Id: string; } interface iDataState { Items: Array<iItem>; } const initialState: iDataState = { Items: [], }; reducers: { updateItem: (state, action: PayloadAc ...

Hiding collapsible navbar in Angular 7 when in responsive mode

Hey there, I'm currently using a navbar in Angular 7 and I'm looking for a way to collapse it when clicking on another area of the page. When resizing my browser or when accessing the app on mobile, the navbar displays a menu icon with three bars ...

ngx-text-diff is failing to update when I programmatically insert HTML attributes

Currently, I am utilizing an npm package called ngx-text-diff to create a file content comparator with great success. After importing its component and ensuring it functions correctly, I encountered an issue. The HTML selector requires two arguments - &apo ...

Using the <Field> component in Vee-validate ensures that your form will always be valid when submitted

Hello all, I am currently working on a Vue 3 project and utilizing vee-validate v4 for form validation. My forms are structured as follows <template> <div> <VForm v-slot="{ meta }" ref="form" > ...

Create a Typescript React class and define the State type as either an interface or null

When working with React and typescript, it is common to declare state types in the following manner: import * as React from "react" interface IState { someState: string } class MyClass extends React.Component<{}, IState> { state = { someSt ...

I am encountering an issue where the JSON data is not being properly loaded into my Angular 8 application

Here is the structure of my JSON data: { "content": [ { "id": 1, "name": "test name", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbbfaeb8bf8bbfaeb8bfe5a8a4a6"&g ...

creating an interactive image with Angular

I am experiencing difficulty in making my image clickable. The image is designed as a cart with a small number bubble indicating the quantity of items in the cart. Although the div itself is clickable, the photo within it is not. Below is my code snippet: ...

Utilize apexcharts to apply custom colors for negative data points

I am currently utilizing apex charts within a react application, and I have a requirement to display markers with different colors if the y value is a negative number. Below is the logic that I am using to extract the values: const colorMarkers = ...

Is there a way to incorporate TypeScript type definitions into a JavaScript module without fully transitioning to TypeScript?

Although the title may be a bit confusing, it encapsulates my query in a succinct manner. So, here's what I'm aiming to achieve: I currently have an npm module written in JavaScript, not TypeScript. Some of the users of this module prefer using ...

What is the mechanism through which ng-bootstrap incorporates the NgbRadioGroup and NgbButtonLabel into their NgbRadio directive in Angular 2?

Below is the code snippet for label: import {Directive} from '@angular/core'; @Directive({ selector: '[ngbButtonLabel]', host: {'[class.btn]': 'true', '[class.active]': 'active', &apos ...

Bundling and minifying Angular2 assets

In the world of ASP.NET (or gulp), bundling and minification are taken care of. However, a different issue arises when following Angular2 tutorials: the view HTML is typically embedded within the component itself. Fortunately, there is a way to separate th ...

Local hosting of Angular 8 application with Universal and i18n integration encountered issues

I have integrated Angular Universal into my existing project that already has i18n. I am able to build the project, but facing issues while trying to serve it. Currently, I am encountering the following error: Cannot find module '/home/my-user/my-ap ...

Trigger a table refresh to display updated information

When I select the select option to make an API call for a new datasource, my table appears before fetching data and it remains empty. Additionally, if I choose another select option, it displays the previous data from the previous selection. I have attemp ...

I'm having trouble figuring out how to access response headers with HttpClient in Angular 5. Can anyone

I recently developed an authentication service in Angular 5, where I utilize the HttpClient class to make a POST request to my backend server. The backend server then responds with a JWT bearer token. Here is a snippet of how my request looks: return thi ...

Comparing two string dates in mongoose: A guide

I am trying to retrieve data between two specific dates in my Schema. transactionDate : String Here is the function I am using to get data between two dates: async getLogsByDate(start, end) { return await this.logModel .find({ date: { $gte: sta ...

What strategy should be employed for creating a database abstraction layer in Angular?

When it comes to Angular, what is the optimal method for implementing a database abstraction layer that functions similarly to a Content Provider in Android? ...

Tips for retrieving JSON files within karma tests

I am currently working on developing a test for my TypeScript class that involves retrieving data from a JSON file. readData<T>(filePath: string): Promise<T> { return Qajax.getJSON(filePath); } For testing purposes, I am utilizing the Jas ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

Using React and Typescript, implement an Ant Design Table that includes a Dropdown column. This column should pass

Next Row: { title: "Adventure", render: (item: ToDoItem) => { //<- this item return ( <Dropdown overlay={menu}> <Button> Explore <DownOutlined /> </Button> </Dropdown&g ...