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

Error: It is not permitted to have multiple instances of the CORS header 'Access-Control-Allow-Origin', nor is it allowed to have the header missing

Having trouble with CORS headers when making an HTTP request from my Angular 7 app (hosted on http://localhost:4200) to my Spring-Boot app (hosted on https://localhost:8924) using Firefox. The Spring-Boot app has a CORS filter that is applied to the reque ...

What is the capability of dynamically generating an index in Typescript?

Can you explain why the Typescript compiler successfully compiles this code snippet? type O = { name: string city: string } function returnString(s: string) { return s } let o1: O = { name: "Marc", city: "Paris", [returnString("random")]: ...

Using .htaccess with Angular is specifically designed to function within a subfolder of

After deploying my app on a Debian 11 Apache server within the folder var/www/html (specifically in var/www/html/foo), I encountered issues with routing and hard refreshing, resulting in a 404 error whenever I attempted to refresh a page. The Angular app c ...

Ways of modifying the readonly and required attributes of an HTML element using Angular2 Typescript

I am facing an issue with changing input field attributes back and forth in some of my components. I have a code that successfully changes the readonly attribute as needed. However, when trying to change the required attribute, Angular2 still considers the ...

Tips on exporting a basic TypeScript class in an Angular 4 module

I am facing a challenge with packaging a TypeScript class as part of an Angular module for exporting it as a library using ng-packagr. For instance, here is my class definition - export class Params { language: string ; country: string ; var ...

Issue with using loadChildren in Angular 11 routing

Once I log in to my app, I navigate to the link: this.router.navigate(['/sellTicket/chooseTicket']); In my app-routing configuration, I have the following setup: const routes: Routes = [ {path: 'login', component: LoginComponent}, ...

Guide to implementing Angular 2 lazy loading with the Visual Studio 2015 ASP.NET Core Template Pack

I am currently working on implementing router lazy loading in Angular 2. My goal is to be able to do something like this: const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full', { path: 'about&apos ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

Setting dynamic values for SASS mixins in Angular 2 with Ionic 2

In my SCSS file, I have created a mixin to generate a progress bar. @mixin progressBarMix($name, $size, $perc, $color, $colorBack) { .progressBarWrapper { &#{$name} { $sizeFill: $size / 100 * $perc; .progressBarEndFilled { b ...

Embedding the Angular Material date picker when the page loads using an HTML tag

Currently, I am in need of a solution where the material datepicker (the datepicker itself, not just the icon) is visible on the page by default. The goal is to always have the datepicker displayed without needing to click on an icon. If anyone could pro ...

Is there a way to effectively refresh in Angular while using JBoss 6.4?

In my configuration of the standalone.xml file, I have set up the following rules inside subsystem tags: <rewrite name="rule-2" pattern="^((?!.*(rest)).*)\/([\w\-]+)\/([\w\-]+)$" substitution="/$1/index.html" flags="L"/> ...

Passing data to a child component using Context in React is not working

I have a parent component where I am storing data in an array of objects and then passing it to another component through Context. Here is how my parent component looks: export type HistoryData = { input: string; date: string; ...

refresh specific route when navigating to the same URL

Can the onSameUrlNavigation: reload be applied to just a single route in Angular? ...

What is the subclass of all object literal types in TypeScript?

With the `strictFunctionTypes` setting turned on, function parameters are checked contravariantly. interface Func<T> { (p: T): unknown } declare let b: Func<{p1: string}> declare let c: Func<{p2: number}> declare let d: Func<{p3: nu ...

Can anyone offer any suggestions for this issue with Angular? I've tried following a Mosh tutorial but it's

Just finished watching a video at around 1 hour and 35 minutes mark where they added the courses part. However, I encountered an error during compilation. ../src/app/app.component.html:2:1 - error NG8001: 'courses' is not recognized as an elemen ...

Tips for storing an unmatched result in an array with a Regexp

Is it possible to extract the unmatched results from a Regexp and store them in an array (essentially reversing the match)? The following code partially addresses this issue using the replace method: str = 'Lorem ipsum dolor is amet <a id="2" css ...

Why won't my Angular app hit a breakpoint while debugging?

I'm relatively new to the world of Visual Studio Code and Angular applications with a C# Web API back-end. My issue lies in hitting breakpoints within my Angular app using VS Code, even though I can hit them without any problems in C#! Running both a ...

Is it possible to utilize AngularfireList without observables? In other words, can I retrieve an AngularfireList object directly from Firebase and then process it in

I am attempting to retrieve an object from Firebase using AngularFire and angularfirelist. However, the returned object is not what I expected. Here is my code: export class AdminProductsComponent implements OnInit { products$ : AngularFireList<unkn ...

When the key property is utilized, the state in react useState is automatically updated; however, for updating without it, the useEffect or a

I am working on a component that looks like this: import React, { useState } from "react"; import { FormControl, TextField } from "@material-ui/core"; interface IProps { text?: string; id: number; onValueChange: (text: stri ...

The 'Refused to execute inline event handler' error occurs when using Angular

I am encountering a specific error in my Angular application when trying to execute an inline event handler. The error message can be seen below: https://i.stack.imgur.com/jSAIz.png Refused to execute inline event handler because it violates the following ...