Angular encountered an error when trying to access the property "fruits" of an undefined object

When working with Angular, I encountered an issue where I received the error message "cannot read property 'fruits' of undefined." Within my class definition, I have included the following:

export class MyClass implements OnInit {

fruits: any[];

doSomething() {
this.myArray.forEach(function(m) {
  const my = { test: true };
  this.fruits.push(my);
  }
}

Since I am considering adding different types to my array, I refrained from defining an interface. What could be causing this problem?

Answer №1

To gain access to this feature, arrow functions are the way to go:

fruits: any[] = [];

doSomething() {
  this.myArray.forEach(m => {
    const my = { test: true };
    this.fruits.push(my);
  }
}

By using arrow functions, you can ensure lexical binding which allows for accessing this from the object context itself (the 'outer' scope). Find out more about it here.

Answer №2

In order to start, you need to set up the fruits

export class myClass implements OnInit {

    public myArray: string[] = ['banana', 'Apple, 'Kumquat']
    public fruits: {test: boolean}[] = [];

    constructor() {}

    ngOnInit() {}

    public doSomething(): void {

      let my: any = {}; 

      this.myArray.forEach( m => {
        my = { test: true };
        this.fruits.push(my);
      });
    }
}

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

The reason behind the clickable issue with my duplicate <ion-select>

I've been working on a form using HTML, CSS, and JavaScript where I implemented an "Add" button to duplicate the form. The issue arises with the ion-select element within the duplicated form. While the original form displays all predefined options upo ...

Struggling to compile your Angular 2 application in Visual Studio 2015?

After carefully following all the steps outlined in the VISUAL STUDIO 2015 QUICKSTART documentation, I have also gone ahead and installed the "Microsoft .NET Core 1.0.1 VS 2015 Tooling Preview 2", even though it was not specifically mentioned in the docume ...

What could be the reason for mocha failing to function properly in a project that is set up

During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows: ➜ typescript-project yarn test yarn run v1.22.17 warning package.json: No license field $ ...

Following an Angular update, the npm installation process encounters issues due to conflicts related to peer dependencies

I am facing challenges with updating my Angular version. When I try to use the command ng update, the output I receive is as follows: Name Version Command to update ------------------------------ ...

Ensure the clarity tabs labels have the padding-left CSS property added

In my project, there are 2 clarity tabs (you can view the StackBlitz reference here). I want to apply the padding-left property specifically to Tab1 (the tab label itself, not the content) in order to create some space around it. Through Chrome Dev Tools, ...

Tips for retaining scroll position in Angular 2

Suppose I am currently on page 1. I scroll halfway through the page and then click a link that takes me to page 2 using the Angular router. When I use the "back" button, I want page 1 to be scrolled halfway down, just like it was before I left the page. H ...

Round off Kendo Column Chart edges and add a personalized highlight shade

Is there a way to create a kendo column chart with rounded borders similar to the image provided? Below is the code snippet I am currently using. Additionally, how can I customize the hover-over color for the columns in the chart? <kendo-chart-series& ...

Tips for calculating the total sum of inner object property values using JavaScript, TypeScript, or Angular 5

What is the total sum of successCount values in the given array object? var successCount;//I want count of all successCount attributes from the below object var accordianData = [ { name: "Start of Day", subItemsData: [ { title: " ...

Issues with displaying data in Angular Material table

I am having trouble displaying data in a table. The data shows up when I display it in another element, but not in the table. Here is my code: <mat-accordion *ngIf="posts.length > 0"> <mat-expansion-panel *ngFor="let post of p ...

TypeScript operates under the assumption that every key will be present on a Record object

Check out this code snippet: declare const foo: Record<string, number> const x = foo['some-key'] TypeScript indicates that x is of type number. It would be more accurate to say x is of type number | undefined, as there is no guarantee th ...

Tips for incorporating a conditional background color in a styled component with react and typescript

Is there a way to dynamically change the background color of a styled component based on a condition using React and TypeScript? What I am attempting to achieve: I have a MainComponent that displays ListContent within a DragAndDropComponent. When a user ...

Angular: Issue with FormArrays not iterating properly

Apologies for the lengthy post, but I needed to provide a detailed explanation of the issue I am facing. In my form, there is a control that contains an array of JSON data. I have created a reactive form based on this structure. Below are the JSON data an ...

Utilize the express library (NodeJS, TypeScript) to send back the results of my function

I am curious about how I can handle the return values of my functions in my replies. In this specific scenario, I am interested in returning any validator errors in my response if they exist. Take a look at my SqlCompanyRepository.ts: async create(compan ...

Having trouble retrieving the value in JSON/PHP, even though the value is present and cannot be echoed

I am facing a minor issue with fetching data from a JSON file. Upon using print_r() to display the data, I can see the fields I need. However, when I attempt to access them, only 2 out of 3 seem to work - one appears to be inaccessible. Below is the code ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

A guide on breaking down a variable into an array using batch scripting

I am currently working on creating a text adventure game using batch scripting and I am looking for a way to split a variable like 'set userinput=take book' into an array. My goal is to develop a program that can divide strings into individual ar ...

Utilizing TypeORM to selectively choose data in OneToMany relationships

I am looking to create a TypeORM query that pulls data from the database. Specifically, I want to retrieve all clients who have made a purchase but have not initiated a return. Here is the structure of the database: Clients: Id (Int, primary column) Purc ...

Collection of functions featuring specific data types

I'm currently exploring the idea of composing functions in a way that allows me to specify names, input types, and return types, and then access them from a central function. However, I've encountered an issue where I lose typing information when ...

How to pinpoint a particular element in a parsed json using Ruby

I have a JSON string that I need to parse using Ruby. The string looks like this : [ { "id": 1, "player_id": "not_this_one\n", "highscore": 23 }, { "id": 2, "player_id&qu ...