Mehrab Shaida
Mehrab Shaida

Reputation: 23

Initialize interface type array in angular 11

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)

Upvotes: 1

Views: 971

Answers (2)

Milan Tenk
Milan Tenk

Reputation: 2685

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'};
}

Upvotes: 2

Chris Danna
Chris Danna

Reputation: 1264

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

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

Upvotes: 2

Related Questions