1

I have created interface with name Test in Angular 11

 export interface Test {
      id:number;
      name:string;
    }

Then I have exported the interface and create its array with name of ProvinceAllStudent

import { Test } from './../../../student/Models/test';
import { Component, OnInit } from '@angular/core';
import { Province } from 'src/app/student/Models/Province.model';
@Component({
  selector: 'app-general-statistic',
  templateUrl: './general-statistic.component.html',
  styleUrls: ['./general-statistic.component.css']
})
export class GeneralStatisticComponent implements OnInit {
Provinces:any[];
ProvinceAllStudent:Test[]=[];

  constructor(
) { }

  ngOnInit(): void {
 this.CalculateProvinceStudents()
  }
  CalculateProvinceStudents()
  {
     for(let j=0;j<5;j++)
     {
      this.ProvinceAllStudent[j].id=j;
      this.ProvinceAllStudent[j].name='A';
     }
  }

}

when I run the application I got the error

core.js:6210 ERROR TypeError: Cannot set properties of undefined (setting 'id') at GeneralStatisticComponent.CalculateProvinceStudents (general-statistic.component.ts:23)

3
  • 1
    Your loop (let j=0;j<5;j++) is going from index 0 to 4, but ProvinceAllStudent is empty. Commented Sep 18, 2021 at 20:12
  • I want to initial the ProvinceAlStudent array using loop Commented Sep 18, 2021 at 20:15
  • In the body of the for loop, You should create a Test object, and then assign it to the array index: ----------> let t : Test = {id: j, name: 'A'}; this.ProvinceAllStudent[j] = t; Commented Sep 25, 2021 at 19:10

2 Answers 2

2

Because this.ProvinceAllStudent[j] is undefined and you try to assign a value to a property of it. (undefined does not have the id and name properties, so an exception is thrown.)

I suggest to use push method of the array. For example

for (let j = 0; j < 5; j++) {
  this.ProvinceAllStudent.push({ id: j, name: 'A' });
}

Or as alternative an alternative you can add elements by index this way:

for(let j = 0; j < 5; j++) {
  this.ProvinceAllStudent[j] = {id: j, name: 'A'};
}
Sign up to request clarification or add additional context in comments.

6 Comments

but if i want to access 0 index value how i can thanks
this.ProvinceAllStudent[0] works, push starts to add the values from the 0th index.
Thanks for solving the problem Milan Tenk
I'm glad, that I could help! Please accept the answer. ;)
ok the push method will insert new item to array can you explain that if i want to insert new item in specific index of an array
|
2

you need to create the object first before modifying it in the array

this.ProvinceAllStudent.push({
  id: j,
  name: 'A'
})

1 Comment

but I want to initial array an index base thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.