What is the best way to retrieve class properties within an input change listener in Angular?

I am new to Angular and have a question regarding scopes. While I couldn't find an exact match for my question in previous queries, I will try to clarify it with the code snippet below:

        @Component({
          selector: 'item-selector',
          templateUrl: './item.component.html'
        })
        export class ItemComponent implements OnInit {

          items: ITem[];  // ITem model with a numeric property 'price'
          totalPrices = 0; // variable to hold total price of items array (sum of item.price)
          
          
          ngOnInit()  {
            items = data from server....
          }

           

          onPricesChange(event): void { // triggered on price change 
            // My question is: how can I access the list of Items here? (to update totalPrices field)
            // this.items returns undefined
           }
           
           
          deleteFromItems(item: ITem) {
             // However, the list of Items (this.items) can be accessed HERE from the click listener !!!
          }
        }

        <tr *ngFor="let item of items">
            <td><input type="number"  [(ngModel)]="item" (input)="onPriceChange($event)">
            </td>
            <td class="text-right">
                <div class="btn-group">
                    <button type="submit" (click)="deleteFromItems(item)"
                            class="btn btn-danger btn-sm">
                        <fa-icon [icon]="'times'"></fa-icon>
                        <span class="d-none d-md-inline" >Delete</span>
                    </button>
                </div>
            </td>
        </tr>

Answer №1

If you want to pass data from your *ngFor loop, you can do so easily. In the code snippet below, I have included item and items in the onPriceChange() function call.

<tr *ngFor="let item of items">
            <td><input type="number"  [(ngModel)]="item" (input)="onPriceChange($event, item, items)">
            </td>
            <td class="text-right">
                <div class="btn-group">
                    <button type="submit" (click)="deleteFromItems(item)"
                            class="btn btn-danger btn-sm">
                        <fa-icon [icon]="'times'"></fa-icon>
                        <span class="d-none d-md-inline" >Delete</span>
                    </button>
                </div>
            </td>
        </tr>
onPricesChange(event, item, items): void { // triggered when a price change occurs
            // The issue lies here: how can we access the list of Items in this function? (to update the totalPrices field)
            // this.items is currently returning undefined
           }

Answer №2

Here are some recommendations you can try:

  1. When in the view, attempt sending the item object instead of $event like this:

    <td><input type="number"  [(ngModel)]="item" (input)="onPriceChange(item)"></td>
    
  2. In the component file, update the onPricesChange() method as follows:

onPricesChange(item: ITem): void { this.items.forEach(data=> {

            if (data.id == item.id) {
                if(data.price != item.price) {
                    this.totalPrices -= data.price;
                    this.totalPrices += item.price;
                } 
            }
            });
       }

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

Utilizing Angular for Webcam Integration

After trying out this code snippet: <video autoplay playsinline style="width: 100vw; height: 100vh;"></video> <script> navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } }) .then(stream =&g ...

Setting up CI/CD for a project involving an API, Angular application, and database on Azure App Services

In my VSTS local GIT REPO, I have a solution file with three main projects: an API, an Angular App, and a SQL Server DB Project. There are also some test projects included in the solution. I am currently facing challenges in setting up CI/CD for this setu ...

Typescript is failing to return nested types when attempting to return a nested object

My goal is for my function to return a nested type of Content, but it's not working even though the type that should be returned is known. Let's take a look at an example: type Content = { some: { extra: string; prop: number; ...

Unable to set up ng-bootstap on Angular version 16.1.3

Upon attempting to integrate ng-bootstrap with Angular 16.1.3, an error was encountered during installation: Would you like to proceed? Yes npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l ...

Fetching a collection from Cloud Firestore using Angular and Firebase

I'm looking to figure out how to retrieve lists from cloud firestore. Here is how I upload a list : export interface Data { name: string; address: string; address2: string; pscode: string; ccode: string; name2: string; } constructor(pri ...

Using both Angular material design and Bootstrap together can provide a seamless

Is it feasible to integrate material design into an Angular app alongside bootstrap without any complications? I am aiming to leverage the grid system of twitter-bootstrap and incorporate the dialogues from material design... ...

Angular Application Functions Properly on Local Machine, Yet Experiences Issues When Deployed on Azure

I've been making the transition from AngularJS to Angular 2 and beyond. I found a tutorial that helped me set up routing with multiple components using Visual Studio IDE, which worked flawlessly on my local machine: However, when I tried to publish i ...

What is the best way to retrieve the Hash value of an object in Typescript?

What is the process for obtaining the hash value of an object in typescript? For instance: let user:any = {name:'tempuser', age:'29'}; let anotheruser:any = {name:'iam', age:'29'}; if( Object.GetHashCode(user) === ...

Can you clarify the definition of component initialization in Angular 2+ specifically in relation to the OnInit lifecycle hook?

As per the Angular documentation on Life cycle hooks at Angular.io, the OnInit hook serves to initialize the directive/component after Angular has initially displayed its data-bound properties and set its input properties. But what exactly occurs when it& ...

Determine the category of a container based on the enclosed function

The goal is to determine the type of a wrapper based on the wrapped function, meaning to infer the return type from the parameter type. I encountered difficulties trying to achieve this using infer: function wrap<T extends ((...args: any[]) => any) ...

How to use RxJs BehaviorSubject in an Angular Interceptor to receive incoming data

Being a newcomer to rxjs, I grasp most operators except for the specific use case involving BehaviorSubject, filter, and take. I am working on renewing an oauth access and refresh token pair within an Angular interceptor. While reviewing various codes fro ...

The object's type remains a mystery

While working on implementing jwt authentication in Ionic, React with TypeScript, I faced a typescript error when trying to add a check in my App.tsx file after successful implementation. The error stated: Object is of type 'unknown' Below is ...

Have you utilized the Remember Me feature on the Angular login page before?

Here is the Angular Html code I have written: <form action="#" [formGroup]="login" (ngSubmit)="onSubmit()" class="login-form"> <label for="email">Email</label> <input type=" ...

An error has been detected: An unexpected directive was found. Kindly include a @NgModule annotation

I am encountering an issue while trying to import a class into a module in my Ionic/Angular app. Upon attempting to release, the following error message appears: ERROR in : Unexpected directive 'SeedModalPage in /home/robson/Lunes/repositories/bolunes ...

Is it possible to have a button within a table that, when clicked, opens a card overlaying the entire table?

I'm having an issue with a table and card setup. When I click the button in the table, the card that appears only covers part of the table. I want it to cover the entire table area based on the content inside the card. How can I make this happen? I&a ...

Creating a dynamic popup/modal in Angular 7 using a service

As a newcomer to Angular, I find myself with a question regarding services. In the past, when working with other languages, I would create self-contained components that could be called from anywhere within the application. Currently, my need for popup di ...

Utilizing Angular to Handle Undefined Variables in String Interpolation

Seeking a way to showcase data obtained from an external API on a webpage using Angular's string interpolation. If no data is retrieved or is still pending, the aim is to display 'N/A'. An attempt was made following this method, but encoun ...

Tips for resolving the AWS CDK setContext error while updating beyond v1.9.0

Attempting to upgrade AWS CDK code from version 1.9.0 to version 1.152.0, I encountered a problem with the setContext code no longer being valid. The error message states ‘Cannot set context after children have been added: Tree’ The original code tha ...

Change the background color of mat-select to match the selected mat-option

<mat-form-field> <mat-select [formControlName]="name"> <mat-option [value]="option.id" [ngStyle]="{backgroundColor: option.color}" *ngFor="let option of list; let i = index" ...

How come JSON.parse is altering the data within nested arrays?

In my journey to master Angular 2, I decided to challenge myself by creating a Connect Four game using Angular CLI back when it was still utilizing SystemJS. Now, with the switch to the new Webpack-based CLI, I am encountering a peculiar issue... The fun ...