Creé una interfaz con el nombre Prueba en Angular 11
export interface Test { id:number; name:string; }Luego exporté la interfaz y creé su matriz con el nombre de 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'; } } }cuando ejecuto la aplicación me sale el error
core.js:6210 ERROR TypeError: no se pueden establecer propiedades de undefined (estableciendo 'id') en GeneralStatisticComponent.CalculateProvinceStudents (general-statistic.component.ts:23)
primero debe crear el objeto antes de modificarlo en la matriz
this.ProvinceAllStudent.push({ id: j, name: 'A' })Porque this.ProvinceAllStudent[j] no está undefined e intenta asignarle un valor a una propiedad. ( undefined no tiene las propiedades id y name , por lo que se genera una excepción).
Sugiero usar el método push de la matriz. Por ejemplo
for (let j = 0; j < 5; j++) { this.ProvinceAllStudent.push({ id: j, name: 'A' }); }O como alternativa, puede agregar elementos por índice de esta manera:
for(let j = 0; j < 5; j++) { this.ProvinceAllStudent[j] = {id: j, name: 'A'}; }