Error: While working in an Angular project, a TypeError occurs because the property '****' cannot be read when used within a forEach loop

As I attempt to iterate over this.data.members and perform certain actions within the forEach loop on this.addedUsers, I encounter a TypeError: Cannot read property 'addedUsers' of undefined. Interestingly, I can access this.data.members outside the forEach loop.

export class AddgroupComponent implements OnInit {
public addedUsers: any[] = [];

constructor(
    @Inject(MAT_DIALOG_DATA) public data: any
    ) { }

ngOnInit(): void {
       this.data.members.forEach(function (item) {
        console.log(this.addedUsers)
      });
    }
  }
}

Answer №1

When attempting to reference the current context inside a forEach loop using ES5 syntax with function (item), you'll find that this is undefined due to the concept of lexical scoping. To access this, it's necessary to utilize an arrow function in ES6 like () => {}.

ngOnInit(): void {
       this.data.members.forEach((item) => {     // use of () => { ... } arrow function
        

        // You may want to add members here
        // this.addedUsers.push(item);

         console.log(this.addedUsers)

      });
    }
}

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

Utilize IntelliJ's TypeScript/JavaScript feature to extract a method from all instances

I am relatively new to using IntelliJ Idea Ultimate 2020 and I am currently exploring the refactoring functionalities within the software. Is there a way to extract a method from a section of code and apply it to all instances easily and exclusively withi ...

Enhancing CKEditor functionality with Angular 2 for improved textarea usage

Check out this Plunker example: https://plnkr.co/edit/aUBtpe?p=preview When using CKEditor, the value of the content variable does not update when changes are made to the textarea. It remains the same as the original page.content variable that was obtaine ...

The combination of React, Typescript, and MaterialUI Paper results in a stunning design with a sleek and

Whenever I include <Paper elevation={0} /> within my react component, I encounter the following issue: Cannot read properties of undefined (reading 'background') TypeError: Cannot read properties of undefined (reading 'background&apos ...

Pause for Progress - Angular 6

I'm looking for a solution to solve the following issue. I need to access a property that will store data from an http request. Therefore, I want to verify this property only after the transaction is completed. validateAuthorization(path: string): ...

Unexpected behavior with Angular 10 behavior subject - encountering null value after invoking .next(value) function

Can anyone help me solve the mystery of why my user value turns null after I log in? This is the login page where an API is called and the result is obtained as shown below: https://i.stack.imgur.com/kDjSy.png Here is the authentication service implemen ...

Error encountered when attempting to format a number using Angular interpolation

Just starting out with Angular and encountering an issue with my custom filter: propertyApp.filter('telLink', function() { return function(tel) { // To avoid interpolating error if(typeof(tel) != undefined) { // Remove any lead ...

A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following: A, B, C, D Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...

The ngx-image-cropper's roundCropper attribute is not functioning correctly as it should. An error is being displayed stating: "Type 'string' is not assignable to type 'boolean'"

<image-cropper [imageChangedEvent]="imageChangedEvent" [maintainAspectRatio]="true" [aspectRatio]="4 / 4" format="jpg" (imageCropped)="imageCropped($event)" roundCropper = "true"> </i ...

Refreshing the display in an AngularJS directive

I've developed a custom directive for handling file uploads in my AngularJS application. The directive is used in multiple places, including on the same page more than once. Each instance of the directive is supposed to display the uploaded file name ...

What are the best practices for handling context in Angular?

Currently, I am focused on enhancing our code base to improve readability and performance. Our approach involves a container component that loads all necessary data and passes it down to child components via Inputs. While this is generally considered good ...

Error encountered when utilizing cursor in Prisma

I am currently utilizing Prisma version 4.2.1 within a Next.js API Route to implement cursor-based pagination for posts. Upon passing the cursor to the API endpoint, I encounter an error message (500) in the console: TypeError: Cannot read properties of u ...

The default choice vanishes once a non-empty option is chosen

Here is a simple example illustrating my issue: JSFiddle. Initially, I have an empty/default option, but when I select something else from the drop-down, this default option disappears. How can I keep this default option visible after making a selection? ...

What is the process for updating the authService in Angular to return an observable using the map function from the previous version?

I recently followed a tutorial on JWT authentication with ASP.NET Core 2 Web API, Angular 5, .NET Core Identity, and Facebook login. The tutorial can be found here. While the tutorial was well-written, it utilized an older version of Angular (I am using An ...

Tips for including a clickable button in an Angular textarea

I am looking for a solution to float a button to the top right corner of a text area in an Angular application. Below is my current code setup, but unfortunately, it does not achieve the desired result: <textarea matInput matInput rows="15" cols="40" ...

Angular 2 Error: Unresolved Promise rejection - Unable to assign value to reference or variable

I'm currently working on an Ionic 2 app that includes a barcode reader feature. However, I encountered the following issue while trying to display data: Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: ; Task: Promi ...

Frontend Development with Angular 7+: A Modular Approach

I'm aiming to develop a frontend application that is modularized, allowing for the release of each module independently. However, I've run into an issue where creating angular modules for each frontend module requires building all modules togeth ...

We are in the process of migrating Angular from version 7 to 16, however, we are facing an issue where one of the libraries is still stuck on version 5, causing a Module not found error related to 'rxjs-com

We recently upgraded an Angular project from version 7 to 16 and we are currently using "rxjs": "~7.8.0". Interestingly, there is no mention of rxjs-compat in the package.json file either. However, during the building process of the application, we encoun ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...

Deleting ion-radio from ion-select component in Ionic v4

Is there a way to remove ion-radio elements generated when calling ion-select with a popover interface? <ion-item> <ion-label>Popover</ion-label> <ion-select interface="popover" placeholder="Select One"> <ion-selec ...