angular displaying incorrect values for counter

Hi there, I am new to using Angular and I'm currently facing an issue with increasing and decreasing product quantity on the cart page. The problem is that in my first index it works fine, but in the second index, the value starts with the first index value when incrementing the counter.

Here is a snippet of my HTML page:

<mat-card class="example-card"  *ngFor="let searched of searchedDataResult; let indexOfelement=index;">
         
            <div class="col-2 ">
               
                <mat-form-field >
                    <button
                      mat-button
                      mat-icon-button
                      matPrefix
                      aria-label="Remove"
                      [color]="getColor()"
                      (click)="incrementValue(-1,indexOfelement)"
                      [disabled]="shouldDisableDecrement(searched._value)"
                    >
                      <mat-icon>remove</mat-icon>
                    </button>
                    <input 
                      matInput 
                      type="number"  id="getval_{{indexOfelement}}"
                    value="{{searched._value}}" 
                       
                      (focus)="setColor('primary')"
                      (blur)="setColor('default')"
                    />
                   
                    <button
                      mat-button
                      mat-icon-button
                      matSuffix
                      aria-label="Add"
                      [color]="getColor()"
                      (click)="incrementValue(1,indexOfelement)"
                      [disabled]="shouldDisableIncrement(searched._value)"
                    >
                      <mat-icon>add</mat-icon>
                    </button>
                  </mat-form-field>
                <button mat-flat-button style="background-color: #1d857b;color:white"  (click)="getaddedmedcine(searched.id,indexOfelement,searched.amount)" > Add To Cart</button>
           
    </mat-card>

This is part of my TypeScript file:

incrementValue(step: number = 1, index: number): void {
  
  this._value += step;
  this.searchedDataResult[index]._value = this._value;
  
 }

I need help on how to reset the initial value to start with 1 for every index when incrementing and decrementing the counter. Any assistance would be greatly appreciated. Thank you!

Answer №1

It is recommended to include an array to keep track of the quantity of each product. Here is a sample implementation:

updateQuantity(step: number = 1, index:number): void {
    this.productQuantities[index] += step;
    this.updatedData[index].quantity = this.productQuantities[index];
}

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

Encountering issues with executing transactions in an Ionic 2 application when utilizing Sqlite functionality from Ionic Native

I am currently working on a project that involves setting up and querying a local sqlite database. I am utilizing the cordova-sqlite-plugin along with Sqlite from Ionic Native. Here is the code snippet responsible for opening the database and creating tab ...

issue with lazy loading Angular module containing a preview component

Greetings everyone! I successfully created an Angular app with lazy loading, but I encountered an issue when trying to open child pages inside modules. Instead of opening within the main page, it redirects me to a new page. Here is my module structure: co ...

The feature 'forEach' is not available for the 'void' type

The following code is performing the following tasks: 1. Reading a folder, 2. Merging and auto-cropping images, and 3. Saving the final images into PNG files. const filenames = fs.readdirSync('./in').map(filename => { return path.parse(filen ...

Exploring Angular's Subcomponents

While working on my application, I encountered a dilemma. I currently pass data from the main component to the subcomponents after pulling it from the API with a single request. Should I continue with this approach or have each component make its own separ ...

Navigating from ASP.NET Core Web API to Angular: Redirecting seamlessly

Seems like I am facing an issue with Angular redirection within ASP.NET Core Web API in a shared deployment scenario. I am using ASP.NET Core 7 for the Web API, which was working fine with ASP.NET Core 6. Here is the build files structure captured in a sc ...

Eliminate all citation markers in the final compiled result

Currently, I am consolidating all my .ts files into a single file using the following command: tsc -out app.js app.ts --removeComments This is based on the instructions provided in the npm documentation. However, even after compilation, all reference tag ...

Is there a way to turn off linting while utilizing vue-cli serve?

I am currently running my project using vue-cli by executing the following command: vue-cli-service serve --open Is there a way to stop all linting? It seems like it's re-linting every time I save, and it significantly slows down the process of ma ...

Rendering an Angular page with data using Node.js

I have a scenario for my website where users need to input a URL with a parameter (an ID) and receive back the corresponding page containing information from the database. I am using Angular4 but I am unsure of how to achieve this. It's straightforwa ...

What is the purpose of having a tsconfig.json file in every subdirectory, even if it just extends the main configuration file?

My goal is to streamline the configuration files in my front-end mono repo by utilizing Vite with React and TypeScript. At the root of my repository, I have set up a tsconfig.json file that contains all the necessary settings to run each project, including ...

Issues with Ajax calls in IOS on Ionic Cordova, functioning properly on Android

After meticulously following the instructions provided on this website, I successfully got my app to work flawlessly on Android and in my Chrome browser using the Ionic server. However, I encountered issues when testing it on an iOS emulator or my actual i ...

Using TypeScript to include a custom request header in an Express application

I am attempting to include a unique header in my request, but I need to make adjustments within the interface for this task. The original Request interface makes reference to IncomingHttpHeaders. Therefore, my objective is to expand this interface by intr ...

Form with placeholders

Is there a way to personalize an email using different variables, like adding special characters such as $, {}, [] around the word to indicate it's a variable? For example, {name}. I'm looking for a plugin compatible with Angular 14+ that can ass ...

Can TSLint and ESLint give a warning when a function is accessed as a property?

There have been instances where I've made this specific mistake, and I'm curious if there are any ESLint or TSLint rules in place that could detect it. if (this.isBrowser && this.imageURL) {.....} private isBrowser(): boolean{ retur ...

The Angular project encounters a failure when attempting to run 'ng serve,' resulting in an emitted 'error' event on the worker

Resolved Issue - Update: It appears that the problem was due to an error in my CSS code: Previous: .title & .smaller { color: $dark-blue; font-family: "Roboto"; font-size: 20px; font-weight: 600; width: fit-content; margin: 0; ...

Transferring data seamlessly from EF .NET Core 6 to Angular

I am facing an issue while trying to fetch data from my ASP.NET Core 6 backend to Angular: Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed export class EmployeesListComponent { em ...

Implement conditional props for a React component by linking them to existing props

In my current project, I am working on a component that has a loading state. The component has an isLoading prop which determines whether the component is currently in a loading state or not: interface CustomImageComponentProps { isLoading: boolean ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

Enhance your MaterialUI Button with a higher order component that accepts a component

I am currently working on implementing a Higher Order Component (HOC) for the MaterialUI Button component: import {Button as MUIButton, ButtonProps} from '@material-ui/core'; import * as React from 'react'; export const Button = (props ...

Neither the child nor the parent are showing the ng-content

I'm working on a project with a child-parent structure and I have the following components: <app-parent> parent component <ng-content select=["parent"]></ng-content> <app-child></app-child> </app-par ...

Managing errors with the RxJS retry operator

I'm facing an issue with my RxJS code where I need to continuously retry a data request upon failure while also handling the error. Currently, I am using the retry operator for this purpose. However, when attempting to subscribe to the retry operator ...