Encountering an error when attempting to store a value in an array of custom types: "Unable to assign properties to undefined (setting 'id')"

My model looks like this:

export class SelectedApplicationFeatures {
id: number; 

}

In my TypeScript file, I imported the model as shown below:

import { SelectedApplicationFeatures } from "src/app/models/selectedApplicationFeatures.model";
selectedApplicationFeatures: SelectedApplicationFeatures[]=[];

When I tried to set values in selectedApplicationFeatures within a function, I encountered an issue. Here is the code snippet:

for (let i = 0; i < _applicationFeatures.length; i++) {

  if (_applicationFeatures[i].featureChecked == true) {

    let j = 0;
    this.selectedApplicationFeatures[j].id = _applicationFeatures[i].id;

    j++;
  }
}

The error message I received was:

"ERROR TypeError: Cannot read properties of undefined (reading '0')".

//_applicationFeatures:

application features array

error

Answer №1

The issue can be found in the variable

selectedApplicationFeatures: SelectedApplicationFeatures[];
. It is recommended to first initialize it as follows:

selectedApplicationFeatures: SelectedApplicationFeatures[] = [];

Instead of assigning an unknown number of elements to selectedApplicationFeatures, it might be better to append them. Check out the solution below:

for (let i = 0; i < _applicationFeatures.length; i++) {
  if (_applicationFeatures[i].featureChecked == true) {
    this.selectedApplicationFeatures.push({id: _applicationFeatures[i].id});
  }
}

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

Angular 5 - Reverting back to the previous state

In my Angular web application, I encounter a scenario where I need to navigate back to the previous state. Let's say I am currently on a page at http://localhost/someURL. On this particular page, users have the ability to search for items and see the ...

Encountered an error while attempting to upgrade to the latest @angular/cli version 1.0.0: Unexpected symbol "<" found in JSON at the beginning of the file

When I was using angular-cli 1.0.0 beta 23, my service was able to fetch a local JSON file for testing without any issues. However, after upgrading to angular/cli 1.0.0, I encountered the following problem: GET http://localhost:4200/json/inputInventory/ ...

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

My current setup includes Node.js version 8.11.2 and Angular CLI version 7.1.2. However, upon running Angular CLI 8.0+, it displays an error stating "You are running version v8.11.2 of Node.js, which is not supported

From the beginning of my project, I encountered a version error which led me to uninstall and delete all Node and CLI files before reinstalling them. However, now when I try to run npm start, I am faced with the following message: The current Node.js vers ...

What is the best location for storing test utilities in Next.js applications?

My Next.js (12.x) React (18.x) project includes Jest (28.x) for testing. While my tests in files like __tests__/Product.test.tsx work smoothly, I encountered an issue when trying to reuse some utils across tests: __tests__/util/my-test-helper.ts export fu ...

Execute the function upon clicking

When I click on an icon, I want it to blink. This is the code in my typescript file: onBlink() { this.action = true; setTimeout(() => { this.action = false; }, 1000) return this.action }; Here is how the action is declared in my ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

Guide for launching Electron on a local host server during development and for production builds

I have a project using Next.js + Electron + Typescript. I used the npx create-next-app --example with-electron-typescript command to generate the initial code. When I run npm run dev (which actually runs npm run build-electron && electron . ), the ...

What is the process for incorporating a standalone custom directive into a non-standalone component in Angular?

Implementing a custom directive in a non-standalone component I have developed a custom structural directive and I would like to use it across multiple components. Everything functions as expected when it is not standalone, but encountering an error when ...

Something went wrong: Unable to access the properties of an undefined variable named 'gametitle'

I am able to see the variables on the html-page, but I encountered an error specifically with the value of the gametitle ERROR TypeError: Cannot read properties of undefined (reading 'gametitle') Below is the content of the ts-file: import { ...

Send the index of the row to the event handler in the table of data

I am currently utilizing a data table component from PrimeNG and have the following template code: <p-column [style]="{'width':'40px'}"> <template let-col let-rowData="rowData" let-rowIndex="rowIndex" pTemplate type="body" ...

Error: The AppModule encountered a NullInjectorError with resolve in a R3InjectorError

I encountered a strange error in my Angular project that seems to be related to the App Module. The error message does not provide a specific location in the code where it occurred. The exact error is as follows: ERROR Error: Uncaught (in promise): NullInj ...

Using Angular2 moment to format a date in a specific way

Encountered an error while using the amTimeAgo pipe from angular2-moment. The error message is as follows: Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not ...

Angular: The CORS issue continues despite configuring proxy.conf.json

I have tried several tutorials in an attempt to resolve my CORS issues, but unfortunately, I have been unsuccessful so far. My server setup is very basic - it responds to get 127.0.0.1:8080/hello by returning the string hello there for testing purposes. ...

What is the rationale behind placing the CSS outside of the React function components, near the imports?

Recently, I encountered an issue with loading CSS inside a React function component using Material UI. Even though I managed to resolve it, I am still intrigued by the underlying reason. Initially, I had something like this setup where I placed both makeSt ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...

Using custom properties from the Material-UI theme object with custom props in Emotion styled components: a step-by-step guide

I have implemented a custom object called fTokens into the MUI theme using Module augmentation in TypeScript This is how my theme.d.ts file is structured declare module "@mui/material/styles" { interface FPalette { ... } interface FTokens ...

Unable to start an expo project in bare workflow using TypeScript

Can someone help me with setting up an expo bare workflow using TypeScript? I ran the command "expo init [project name]" in my terminal, but I can't seem to find the minimal (TypeScript) option. ? Choose a template: » - Use arrow-keys. Return to sub ...

Launching in dynamically loaded modules with bootstrapping

The Angular Guide explains that during the bootstrapping process, components listed in the bootstrap array are created and inserted into the browser DOM. However, I have noticed that I am unable to bootstrap components in my lazy loaded feature modules. E ...

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...