Creating a type array for the interface in Angular 11

A newly created interface named Test in Angular 11 contains the following properties:

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

After exporting the interface, an array named ProvinceAllStudent was created to store test data.

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

}

An error occurred when running the application:

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

Answer №1

When trying to assign a value to a property of this.ProvinceAllStudent[j], an exception is thrown because this.ProvinceAllStudent[j] is undefined. (undefined does not have the id and name properties)

One suggestion is to use the push method of the array. For example:

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

Alternatively, you can add elements by index like this:

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

Answer №2

To make changes to an object in the array, it is necessary to first initialize the object.

this.ProvinceAllStudent.push({
  id: k,
  name: 'B'
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for reusing a Jest mock for react-router's useHistory

When testing my code, I set up a mock for the useHistory hook from react-router-dom like this: jest.mock("react-router-dom", () => ({ useHistory: () => ({ length: 13, push: jest.fn(), block: jest.fn(), createHref: jest.fn(), go ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

Error: Unable to call function onPopState from _platformLocation due to TypeError

After building an angular application, I encountered a strange issue where it runs smoothly in non-production mode but throws an error when running with --prod: Uncaught TypeError: this._platformLocation.onPopState is not a function I have double-checked ...

Creating a redirect feature within an Angular application may lead to a null injection issue

My goal is to develop an Angular (version 11.2.9) routing service that will facilitate automatic redirection of users from one page to another within the site. For instance, a guest user visiting the site can log in to their account by clicking on a butto ...

Tips for configuring the cookie expiration date using the ngx-cookie-service library

Can anyone offer assistance with setting the expire date for cookies in my Angular 5 app using ngx-cookie-service? Here is what I have tried: setCookies($event){ this.cookieService.set( 'retailAppCookies', "true", 30 ); this.cook ...

Can you explain the meaning of `(error: T) => void` in error?

I've come across this particular syntax in a few Typescript libraries and I am trying to grasp its meaning. error?: (error: T) => void I have seen it being used like so: class SomeClass { someFunction(error?: (error: T) => void){ } ...

Despite the availability of data, the payload in redux remains consistently undefined

I am facing an issue with my Next.js application that uses redux/redux saga. When data is received from the backend (verified in the browser's network tab), it is being sent to the reducer as undefined. I initially thought it could be due to the paylo ...

Angular theme needs favicon update - closed

In my Angular application, I am creating a dynamic page and I need to change the favicon based on the client. If the client is tesco, then the favicon should be the tesco favicon. Do you have any suggestions for accomplishing this using only Angular, with ...

Angular 4: Converting JSON Data into CSV Format

Can anyone assist me in converting a JSON file to CSV in Angular 4? Is there an existing external plugin that can help with this task? I came across a plugin called json2csv. However, I'm unsure of how to integrate it into my Angular 4 project. ...

Problem: When trying to access the property 'completed' of an object in Angular 2, an error is

My understanding is that by using @Input(), this component should be able to bind <experiment [experiment]="experiment.completed"></experiment>. Here is the hierarchy: https://i.stack.imgur.com/6UwHt.png experiment.detail.component.ts import ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

A guide to dynamically updating key values in an array of objects using Typescript

Within my array called objectArray, I have an object with keys representing different types of clothes. const objectArray: clothesTypes[] = [ { trousers: 90, 'skirts and jackets': 47, scarfs: 100, }, ] I also have another array na ...

Developing a Generic API Invocation Function

I'm currently working on a function that has the capability to call multiple APIs while providing strong typing for each parameter: api - which represents the name of the API, route - the specific route within the 'api', and params - a JSON ...

Implement new functionalities within JDL Jhipster for an Angular project

For instance, I am interested in incorporating functions such as onChange, focusout, onBlur, onClick while passing an extra parameter in jdl like this: <input type="text" class="form-control" name="firstName" (onChange)= ...

Running automated unit tests to ensure browser compatibility for newly written Angular framework code

Can automated JavaScript unit tests be used to assess browser compatibility? I need to conduct dom test cases on my angular 6 code in various browser environments. These unit tests must be able to run during the CI build. ...

A function that retrieves an array containing each individual element from a multi-dimensional array

In my system, I have two essential objects: Order and ProductOrder. Order Object: { id:number; productOrders: ProductOrder[]; } ProductOrder object: { id: number; productName: string; } Currently, I store an array of Order objects in a variable called o ...

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

Create a function that can accept either no parameters or one parameter depending on the input parameter provided

Do you think there is a more efficient way to write this code? The function Z can be called with either one parameter or with no parameters. If the parameter Y is passed in, then the function z(y) is returned, otherwise just run the function z() async x ...

Tips for sending parameters in Next.js without server-side rendering

I followed the documentation and tried to pass params as instructed here: https://nextjs.org/docs/routing/dynamic-routes However, I encountered a strange issue where the received params are not in string format. How is it possible for them to be in an arr ...

Testing the angular components for material chips with input to ensure accurate functionality

I am currently facing an issue while trying to set up a unit test for the mat-chips element. The error message I am encountering is: "Can't bind to 'matChipInputFor' since it isn't a known property of 'input'." It seems that t ...