Search code examples
angulartypescriptmodelpropertiesundefined

On trying to save value to an array of custom type. getting "Cannot set properties of undefined (setting 'id')"


I had created a model like this:

export class SelectedApplicationFeatures {
id: number; 

}

and used it in my ts file as:

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

then if I try to set values in selectedApplicationFeatures in my function like this:

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

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

    let j = 0;
    this.selectedApplicationFeatures[j].id = _applicationFeatures[i].id;
//error is happening on the above line. _applicationFeatures[i].id is returning proper integer value.
    j++;
  }
}

I am getting an error: "ERROR TypeError: Cannot read properties of undefined (reading '0')".

//_applicationFeatures:

application features array

error


Solution

  • The error lies in the variable selectedApplicationFeatures: SelectedApplicationFeatures[];. You should initialize it first as:

    selectedApplicationFeatures: SelectedApplicationFeatures[] = [];
    

    And then, instead of assigning an unknown number of elements to selectedApplicationFeatures maybe appending would be better. Take a look at the fix below:

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