Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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)

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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

this.ProvinceAllStudent.push({
  id: j,
  name: 'A'
})
over 4 years ago · Santiago Trujillo Denunciar

0

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'};
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda