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

"Code snippets customized for React are not functioning properly in the javascriptreact.json file within Visual Studio Code

I'm looking to incorporate some customized React.js code snippets into my Visual Studio Code setup. I am aware of the two files in VSCode that handle this - javascript.json and javascriptreact.json. Although the snippets work well in javascript.json, ...

Issue encountered in IE9 and IE10 when loading the angular library results in the "SCRIPT5007: Object expected" error for Angular JS

I am currently working on an AngularJS application that needs to be compatible with Firefox, IE 9, and IE 10. We are using the latest version of the AngularJS library (currently at 1.3.15). Our serverside is based on Java in the JavaEE platform, running on ...

Sending SMS from an Angular application to mobile devices can be achieved through several methods

Does anyone have experience sending SMS from an Angular6 web application? I would appreciate any guidance, such as reference links or code samples. Thank you! ...

Ajax request causing bootstrap success message to have shorter visibility

I encountered an issue with my ajax form that retrieves data using the PHP post method. Instead of utilizing the alert function in JavaScript, I decided to use a bootstrap success message. However, there is a problem as the message only appears for less th ...

Creating interactive network visualizations using JavaScript

I've been in search of javascript code that can help me create a visual representation similar to this example. Specifically, I need something that can display links between boxes when clicked on or hovered over. I'm still not sure what this par ...

Converting Axios URL Parameter to Array of Strings in ExpressJS

How to Send a GET Request using axios: await this.client.get('/endpoint', { params: { query: ['max', 'kevin'] } }) This will result in a URL that looks like this: Request GET /endpoint?query[]=max&query[]=kevin Any sugge ...

A guide to incorporating dhtmlx scheduler into your Angular 4 project

Currently, I am utilizing dhtmlx scheduler to handle my events. While I was able to import the necessary js files successfully, I have encountered an issue when it comes to saving data in the database. My backend is built using Spring Boot framework. Can ...

Learn how to easily display Firebase data in a user-friendly HTML table with flexible columns, or seamlessly integrate it into an Angular MAT Table

https://stackblitz.com/edit/dynamic-columns-mat-table This is the current status of my table implementation. The table renders perfectly, but my need is to dynamically set column names without prior knowledge. For instance: Instead of ${element.descript ...

Issue with Ionic toggles not updating the correct local storage entry

Encountering an issue with ionic toggles where changing any toggle affects only the last if statement below in local storage. Here is the list of toggles... $scope.settingsList = [ { text: "GBP", checked: gbpON }, { text: "USD", checked: usdON } ...

Exploring the basics of caching in Node.js and Express: a beginner's

Picture an application with numerous users and small sets of data (up to 10 name/value pairs), but the process to access this data involves complex calculations. The concept is based on a system with a 'history' state that is crucial for obtaini ...

AWS Lambda, where the billing time exceeds the actual processing time

While working on my Lambda function in Node.js, I noticed a significant difference in the time measured from the start to the end of the function compared to the billed duration provided by Lambda. The function itself takes around 1400 milliseconds to exec ...

When utilizing Expo, importing a module may result in returning null

I've been attempting to incorporate a compass module into my project using expo and react native, but I'm encountering some issues. Check out the library here The problem arises when I try to import the module. Here's the error message I r ...

Combining the inline JavaScript linting tool ESLint with the popular Airbnb configuration and Facebook

In my current project, I am utilizing ESLint and looking to incorporate Facebook flow. However, I am encountering warnings from ESLint regarding flow type annotations. Within the project root directory, I have both .flowconfig and .eslintrc files present. ...

Triggering multiple onClick events in React / Material-UI when used within a data.map() loop

My English may not be perfect. {data.sort(getSorting(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map(n => { {/*........*/} <Button onClick={this.handleLsClick}> Open Menu < ...

Customize the border width and color of a specific column in HighCharts based on dynamic data

I am looking to dynamically change the border width and color of only one column in a basic column chart. Here is an example: var chartingOptions = { chart: { renderTo: 'container', type: 'column' }, xAxis: { categories: [ ...

Is there a way to automatically import all images from a folder in VUE?

I'm attempting to automatically import all images from a folder. Here is what I've tried under // tested: <template> <p>classical art</p> <img v-for="image in images" :key="image" :src="image.url& ...

Using the useRef hook in a TypeScript project to retrieve a boolean value

As I work on developing an application using Nextjs, I have encountered an issue while using react useRef with typescript. The problem arises when I use useRef without typescript, everything works smoothly. However, the moment I include HTMLDivEleement as ...

Is there a way to utilize AJAX to submit a request to a PHP XML-RPC server?

To communicate with my XML-RPC PHP server from a PhoneGap app, I intend to send an XML-RPC request using AJAX. The request should contain the method, parameters, and all necessary details. ...

Why is my JSON object being mistakenly interpreted as a string literal during iteration?

I'm facing a seemingly simple question but I can't seem to figure it out. Below is the jQuery code I am working with: $(function() { $.get(urlGetContainerNumbers, function(data) { console.log(data); for (var idx = 0; idx &l ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...