Increase the totalAmount by adding the product each time

Can someone help me understand why the totalAmount shows as 20 when I add a product? Also, why doesn't it increase when I try to increment it? Any insights would be appreciated.

Thank you.

ts.file

     productList = [
    { id: 1, name: 'Louis Vuis', price: 10, qtn: 1 },
    { id: 2, name: 'shubert helmet', price: 20, qtn: 1 },
  ];

  productArray: any = [];

  totalAmount: number;

  ngOnInit() {
    this.totalPrice();
  }

  add(product, idx) {
    const found = this.productArray.find(
      item => JSON.stringify(item) === JSON.stringify(product)
    );
    if (found) {
      this.productArray[idx].qtn++;
    } else {
      this.productArray.push(product);
    }
  }

  totalPrice() {
    this.productList.forEach(item => {
      this.totalAmount = (item.qtn * item.price)
      console.log(this.totalAmount);
    });
  }

https://i.stack.imgur.com/5BDYy.jpg

Answer №1

There seems to be an issue elsewhere in the code. I believe you are on the right track.

calculateTotalPrice() {
    this.productList.forEach(item => {
      item.total = (item.quantity * item.price);
      console.log(item.total);
    });
  }

However, you are looping through the JavaScript object and assigning the value to total amount.

If you want to display the price of each item based on quantity while iterating, you should assign the value to a new key within the product object.

For example:

item.total = (item.quantity * item.price);

If you want to show the total sum of all values in totalAmount, you will need to do

this.totalAmount += (item.quantity * item.price)

Additionally, when you increment the quantity by 1, update the state and call this.calculateTotalPrice()

Answer №2

There are a couple of issues to address:

  1. One issue is that when you add a product, it gets added to productArray, but when calculating the totalAmount, you are actually calculating from productList. This leads to a constant totalAmount regardless of how many products are added to the productArray.

  2. Another issue is with the line

    this.totalAmount = (item.qtn * item.price)
    , which simply reassigns the updated value to totalAmount instead of adding it to the previous value. To fix this, you should use
    this.totalAmount += (item.qtn * item.price)
    .

I have made some updates to the totalPrice method in an attempt to rectify these issues. Here is the modified code:

totalPrice() {
    this.productList.forEach(item => {
      let productIndexInProductArray = productArray.findIndex(p => p.id === item.id);
      if(productIndexInProductArray > -1) {
          this.totalAmount += (productArray[productIndexInProductArray].qtn * item.price)
          console.log(this.totalAmount);
      }
    });
  }

Answer №3

currentTotal: number=0;
this.currentTotal += (item.quantity * item.cost) 

Answer №4

Issue: The variable totalAmount is defined but not initialized. Therefore, the first step is to initialize it like so:

totalAmount: number = 0;

Another change needs to be made in the totalPrice function. Currently, every time you calculate the amount for an item, it sets that item's amount as the total amount. This results in the total amount being reset with each new item, leading to only the last item's amount being displayed in the console. To fix this, the item's amount should be added to the total amount as shown below:

totalPrice() {
  this.productList.forEach(item => {
    this.totalAmount += (item.qtn * item.price)
    console.log(this.totalAmount);
  });
}

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

inputting a pair of parameters into a function

While creating an action for react-redux, I encountered a problem when trying to pass two variables into the function - dispatch and hosts. Strangely, the variable host is being logged as a function instead of its actual value. This is my code: export fu ...

The For loop causing crashes in the Filter button functionality

I am currently working on implementing a buy it now only filter button for listings that allow that option. However, I am facing an issue where the app crashes when the button is clicked due to a for loop in my code. Strangely, if I remove the for loop, ...

One-of-a-kind browser identification for users, no login required

I have an online boutique and I want to enable customers to make purchases without creating an account. To achieve this, I need a way to associate a selected list of items with a user. Initially, I considered using the IP address for this purpose but fou ...

What might be causing res.download to retrieve a zip file that is empty?

Using expressjs for my app development, I have created a service to download files on the client side using res.download(filepath, filename). The following is the code snippet of my service: router.route('/downloadFile').get(function(req,res){ ...

What is the best way to loop through a group of WebElements, and only log the results that contain a specific substring?

In my test case, I'm utilizing Mocha to handle the scenario. The test appears to be passing successfully, however, no logs are being printed... it('Is 'Mooooooo!!!! I2MaC0W' a Substring in Results?', function() { this.timeout(50 ...

Having difficulty identifying duplicate sentences in Vue.js when highlighting them

I am looking for a way to identify and highlight repetitive sentences within a text area input paragraph. I attempted the following code, but unfortunately, it did not produce the desired result. highlightRepeatedText(str) { // Split the string into an ...

Swapping out characters that are not numerical within a text input field

Is there a way to restrict the input in a text box to only numbers (1-5), a $(dollar) .(decimal) and '(singlequote) during a keyup event? I need a method that will replace any characters typed that are not part of this criteria with a *. Can you pleas ...

Troubleshooting a Problem with JSON Array in JavaScript/jQuery - Understanding Undefined Values

Currently, I am fetching data from a JSON file: [ { "video": "video/preroll" }, { "video": "video/areyoupopular" }, { "video": "video/destinationearth" }] I have attempted to use console.log at different stages and encountered an issue when p ...

The function res.sendFile() seems to be unresponsive

While building my server-side application using node.js, express, and request-promise, I encountered an issue with the res.sendFile() function in my server.js file. Despite including res.sendFile(__dirname + '/public/thanks.html'); within a .then ...

Exploring React-Query's Search Feature

Looking for guidance on optimizing my Product search implementation using react-query. The current solution is functional but could be streamlined. Any suggestions on simplifying this with react-query would be greatly appreciated. import { useEffect, use ...

Transfer the index of a for loop to another function

Can you explain how to pass the 'i' value of a for loop to a different function? I want to create a click function that changes the left position of a <ul> element. Each click should use values stored in an array based on their index posi ...

I encountered an issue while attempting to manipulate/retrieve the JSON value using REGEX, resulting in an undefined return

I am attempting to retrieve the currency value from a JSON file and if it is USD, then I want to change it to AUD. When trying to find the currency attribute in the JSON file, it returned 'undefined' as shown below: Code: var datastring = JSON. ...

How can two distinct sachems be returned in an http get request using res.json()?

There are two schemes that I have created: Sales and Abc I would like to send a response that includes the documents for both schemas: router.get('/', function(req, res) { Sales.find(function (err, sales) { if (err) return next(err) ...

The Response Header for JWT in Angular2 Spring Boot is not appearing

I am encountering an issue with my Angular2 client, Angular-cli, Spring Boot 1.4.0, and jwt setup. When I sign in from my Angular2 client, I am unable to retrieve the jwt token. My security configuration is as follows: @Configuration @Order(SecurityPrope ...

Creating a Docker image for an Angular application with Node.js

Currently, I am attempting to develop an Angular application within a Docker environment and then run it as a container locally using Node.js. I have utilized the following Dockerfile to build the image, however, I am unsure of what might be missing when ...

Angular 5 experiences a single catchError event for two unsuccessful http calls

I recently implemented Observable.zip in my code to manage multiple observables concurrently. Observable.zip(observable1, observable2).subscribe(([res1, res2]) => doStuff()) The observables observable1 and observable2 represent HTTP requests, and I ha ...

Issues with the functionality of Angular 2 routerLink

Unable to navigate from the homepage to the login page by clicking on <a routerLink="/login">Login</a>. Despite reviewing tutorials and developer guides on Angular 2 website. Current code snippet: index.html: <html> <head> ...

What is the best way to send data from a header component to a separate container component?

Utilizing React-router-dom, I am able to seamlessly switch between components in the following setup: <Router> <div> <Header /> <NavigationBar /> <Switch> <Route exact path ...

What is preventing my video from filling the entire screen?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=d ...

Adding options to a dropdown list dynamically within a ASP.NET Datagrid using Jquery

While the function in my 'aspx' page is functioning properly, I am facing an issue with the 'dropdown' inside the GridControl. It appears to be getting duplicated from the original row and not updating with the values from the appended ...