What steps should I take to prevent inadvertently altering a different text box while utilizing two-way binding for quantity?

Currently, I am using *ngFor within my mat-card to display data from my book table. I have also included a textbox on each card for users to input the quantity they wish to purchase. To achieve this, I utilized two-way binding on the textboxes. However, I encountered an issue where changing the quantity in one textbox affects all the other textboxes as well. How can I prevent this from happening? You can refer to the image below:

https://i.sstatic.net/81Mnm.jpg

Below is a snippet of my code:

store.component.html

<div class="card-container"> 
    <mat-card *ngFor="let card of obs | async; let i = index" class="mt-3">
        <img mat-card-image src="{{card.bookimage}}" width="100" height="200">
        <mat-card-header>
            <mat-card-title>{{card.bookname}}</mat-card-title>
            <mat-card-subtitle>&#8369;{{card.bookprice.toFixed(2)}}<span *ngIf="card.bookunitstock === 0" class="status text-white bg-danger mx-2">Out of Stock</span></mat-card-subtitle>
        </mat-card-header>
        <mat-card-actions>
            <input type="number" [(ngModel)]="quantity" name="quantity">
            <button mat-raised-button color="primary" (click)="onAddToCartProduct(card)"><mat-icon class="me-2">add_shopping_cart</mat-icon>Add to cart</button>
        </mat-card-actions>
    </mat-card>
</div>

store.component.ts

public onAddToCartProduct(book: Book): void {
    const formValue = {
      bookid: book.bookid,
      bookimage: book.bookimage,
      bookname: book.bookname,
      bookprice: book.bookprice,
      bookstatus: book.bookstatus,
      cartitemid: 0,
      category: "Fantasy",
      checkoutstatus: true,
      isbn: book.isbn,
      quantity: this.quantity,
      sku: book.sku,
      totalprice: book.bookprice * this.quantity,
      user_userid: 4
    }
    console.log(formValue);
    this.storeService.addCartProduct(formValue).subscribe(
      (response: Store) => {
        this.products.push(formValue);
        this.grandTotal += (formValue.quantity * formValue.bookprice);
        this.successMessage("added");
    
      },
      (error: HttpErrorResponse) => {
        this.errorMessage("Out -of Stock");
      }
    );
  }
  

Answer №1

One reason for this issue is the usage of the property this.quantity across all cards in the loop let card of obs, causing them all to reference the same property.

Instead, consider binding to the quantity prop individually on each card using

[(ngModel)]="card?.quantity"
.

Also, remember to update the quantity: book.quantity when changing the formValue.

It's important to be consistent with object naming, whether it's a book or a card. Good luck!


Another option is to use a template variable. Take the input value from #myInput and pass it to the method onAddToCartProduct().

        <mat-card-actions>
            <input type="number" #myInput name="quantity">
            <button mat-raised-button color="primary" (click)="onAddToCartProduct(card, myInput.value)"><mat-icon class="me-2">add_shopping_cart</mat-icon>Add to cart</button>
        </mat-card-actions>
public onAddToCartProduct(book: Book, inputValue: number): void {
    const formValue = {
      bookid: book.bookid,
      bookimage: book.bookimage,
      bookname: book.bookname,
      bookprice: book.bookprice,
      bookstatus: book.bookstatus,
      cartitemid: 0,
      category: "Fantasy",
      checkoutstatus: true,
      isbn: book.isbn,
      quantity: inputValue, // <-----
      sku: book.sku,
      totalprice: book.bookprice * inputValue, // <-----
      user_userid: 4
    }
    console.log(formValue);
    this.storeService.addCartProduct(formValue).subscribe(
      (response: Store) => {
        this.products.push(formValue);
        this.grandTotal += (formValue.quantity * formValue.bookprice);
        this.successMessage("added");
    
      },
      (error: HttpErrorResponse) => {
        this.errorMessage("Out -of Stock");
      }
    );
  }

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

How can user-side access rights be dynamically granted to a database in PHP?

Seeking a solution to dynamically assign access rights such as edit, view, and delete values in the database for users using PHP. This will allow the super admin to easily change privileges within the application interface without having to manually upda ...

The script is not functioning properly when placed outside of the HTML body tag

I have a main template that is functioning properly with the layout I've included here. However, I am facing an issue when trying to organize the scripts within one block. Specifically, when I move one of the scripts from the body section to the head ...

Escaping an equal sign in JavaScript when using PHP

I am currently working on the following code snippet: print "<TR><TD>".$data->pass_name."</TD><TD><span id='credit'>".$data->credit_left."</span></TD><TD><input type='button' val ...

The useAutocomplete function in Material-UI fails to consider the disabled

Currently, I am working on developing my own Autocomplete component by utilizing the useAutocomplete hook from the mui/base package. Most parts of the implementation are functioning correctly, except for the disabled option. My expectation is that the com ...

The duration of token validity in Node.js using JWT never ceases

When I create a JWT token using jsonwebtoken and set it to expire after 5 minutes, the token never actually expires. The issue is that I always get the iat (issued at) and exp (expiration) times as the same timestamp, as shown in the log below: { sub: ...

Ways to dynamically retrieve a key value pair in JavaScript and React

I am currently working with a spreadsheet element where the cell values are stored in an object structure like this: localCells = {A1: {input: 'hi', value: 'world'}, A2: {input:'how', value:'you?'}} The object is q ...

Issues with submitting data using jQuery AJAX PUT request

I have a PHP script with the following content: if ($_SERVER['REQUEST_METHOD'] === 'PUT') { echo '{ "response": "' . $_REQUEST['id'] . '" }'; } Now, I am trying to use jQuery to make an AJAX request t ...

Explore the world of textures transferring from Maya to Three.js

I'm looking to convert a Maya model to JavaScript for a simple model with textures. The conversion works fine, but the textures are not showing up. Here is my code: var loader = new THREE.JSONLoader(); loader.load( "models/t2.js", function(geometry) ...

Creating CSS3D matrices

My goal is to achieve a specific effect using CSS3 and JavaScript, creating a MouseOver effect when the mouse moves over the center div. I've developed a small library that takes in three arguments (element, sourcePoints, destination points) and retu ...

Express has made the change from "%2F" to "/" in URLs

In the Express middleware server.get('/abc/test', function(req, res) { var token = req.param('access_token') return app.render(req, res, "/abc", { token: token }); }); This setup will direct all https://domain/abc/ ...

Retrieving object by a value within a nested array in Javascript

I need to retrieve all objects that have a specific 'id' within a nested array. Specifically, I want to find all person objects with hobbies id of 2 (hiking) in the provided sample data. This inquiry tackles the challenge of extracting all value ...

SvgIcon is not a recognized element within the JSX syntax

Encountering a frustrating TypeScript error in an Electron React App, using MUI and MUI Icons. Although it's not halting the build process, I'm determined to resolve it as it's causing issues with defining props for icons. In a previous pro ...

Unlocking the Power of VueJS Mixins in an External JS Library

I'm currently using a 'commonLibrary.js' in my Vue application. One of the functions in this library that I find particularly useful is: var defaultDecimalRounding=3 function formatNumber(number) { if (isNaN(number.value) == tr ...

Using JQuery to append elements and then locate them with the find method does not produce the expected

Hey there, I'm having trouble inserting one DOM element into another. It's something I've done many times before successfully, but for some reason it's not working this time and I can't figure out why. Currently, I am using an Aja ...

Using Angular Typescript, implement a live chat feature that generates link previews

I am having trouble creating a link preview in live chat on my website. I want the preview of a dropped URL to show in the chat window, which requires extracting meta-data from the element of the resource (in that URL) like: <meta property="og:imag ...

What is causing the 'transitionend' event to trigger multiple times?

Currently, I'm honing my JavaScript skills by taking on the 30 days of JavaScript challenge. I'm puzzled by why the 'transitioned' event is triggered twice in the code snippet below. My CSS only contains one property called transform, ...

Retrieve the complete line of text from both a textarea and an editable div

When I right-click inside a textarea, the entire line regarding the current cursor position is displayed. I am trying to achieve the same with an editable div, but it's not working. The console is empty, showing an empty string. Can someone please hel ...

Animating background images using a single data attribute

I'm attempting to create a smooth animation between different background images stored in a single data attribute. The goal is for each image to load sequentially, with the first one appearing immediately and the rest following after a 5-second delay. ...

Unable to retrieve json data from php server

I am new to php and wordpress. I'm attempting to create a basic plugin that will display the 3 most recent posts on a page. Initially, I planned to retrieve a JSON-encoded array and work with it using JavaScript. However, there seems to be an error in ...

What is the solution to resolving the warning about the router no longer defaulting the history prop to hash history?

I have implemented browser history in my code within routes.js export default ( <Router history={browserHistory}> <Route path="/" component={Main}> <Route path="home/:username" component={Home}> <IndexRoute co ...