Determining cost using Ionic based on given text

I'm looking to develop a straightforward shopping list application that includes pricing details.

Here is my shopping.html code snippet:


    <ion-header>
      <ion-navbar color="secondary">
        <ion-title align="center">
          My Shopping Tracker
        </ion-title>
        <ion-buttons end>
          <button ion-button icon-only (click)="addItem()"><ion-icon name="cart"></ion-icon></button>
        </ion-buttons>
      </ion-navbar>
    </ion-header>

    <ion-content>
      <ion-list>
        <ion-item *ngFor="let item of items" (click)="viewItem(item)">{{item.type}}</ion-item>
      </ion-list>
    </ion-content>

    // More content here...

This is the addshopping.html markup:

<ion-header>
  <ion-toolbar color="secondary">
    <ion-title>
      Add Shopping List
    </ion-title>
      <ion-buttons end>
        <button ion-button icon-only (click)="close()"><ion-icon name="close"></ion-icon></button>
      </ion-buttons>
    </ion-toolbar>
</ion-header>

// Rest of the code...

In my addlist.ts file, I have defined the functionality for adding items to the list:


import { Component } from '@angular/core';
import { NavController, ViewController } from 'ionic-angular';

@Component({
  selector: 'page-addlist',
  templateUrl: 'addlist.html'
})
export class AddListPage {

  type: string;
  description: string;
  today: Date;
  total: price;
  
  constructor(public navCtrl: NavController, public view: ViewController) {}

  saveItem(){
    let newItem = {
      type: this.type,
      today: this.today,
      description: this.description,
      total: this.total,
    };

    this.view.dismiss(newItem);
  }

  close(){
    this.view.dismiss();
  }
}

One question I have is how can I calculate the total price every time I add a new item and display it on the footer section? Any suggestions or tips would be greatly appreciated!

https://i.sstatic.net/GS9JD.png

Also, should I keep the values as strings or convert them to numbers for better calculation accuracy?

Answer №1

To determine the overall cost, consider using a function that sums up all the prices as shown below:

function calculateTotalPrice() {
    let totalPrice = 0;
    for (let product of products) {
      totalPrice += parseFloat(product.price);
    }
    return totalPrice;
}

You can then invoke this function in the footer section like this:

[(ngModel)]="calculateTotalPrice()"

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

What is the proper way to incorporate loops with Discord reactions?

Recently, I've been facing some challenges while coding a fighting Discord bot game! The game mechanics involve rolling dice to determine the player who starts, then the winner rolls two more dice to calculate the inflicted damages before passing the ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

The jQuery .on('click') event is only functioning properly the first time it is clicked

Recently, I encountered a peculiar issue with an on-click event that seems to work only once. The intended functionality is to toggle the .p-active class, but instead, it only adds it. The problem arises from dynamically added content post-click using lig ...

delayedExecution function

I have been extensively researching my issue and want to avoid posting a duplicate question. Despite trying the methods suggested in my research, I am unable to get my function to delay as intended! Could someone please review my syntax and help me identi ...

The CSS files undergo modifications when executing the command "npm run dev"

I've been working on an open-source project where I encountered a bug. Even when there are no images to display, the "Load More" button in the web browser extension still appears. To fix this, I decided to add the class `removeButton` to the button an ...

How can I compel npm to resolve dependencies flatly?

I am working on a project where multiple frontends share a common library. The module dependencies for these projects are managed using npm. In the package.json file of each project, I specify: "dependencies": { "mylib": "file:../<...path...> ...

Prevent AngularJS from entering endless digest loops by incorporating unpredictable content

One of the main components in my structure is an <img ng-repeat="img in api.images" src="{{ img.url }}"> The api object contains a list of image IDs and needs to make HTTP calls to retrieve the URLs for each image ID from the server. However, these ...

Innovative ways to design a responsive carousel with Bootstrap

My goal was to create a slider with divisions inside a bootsrap carousel, and here is what I did. However, I am looking for guidance on how to adjust it so that on screens smaller than sm (of bootstrap), there are only two divisions in one carousel, and a ...

Having trouble retrieving information from an external local json file

I'm attempting to display an 'alert' box containing text retrieved from a JSON file. However, I'm facing issues in fetching data from the JSON file and the alert box is not being displayed. var thebook = JSON.parse(book); function s ...

Showing AJAX response on input fields

<table class="table table-bordered responsive"> <thead> <tr> <th>Session</th> <th>Bus Route</th> <th>Charges</th> <th> ...

Using THREE.js: Object3D Dimension Shrinkage

Is there a way to disable sizeAttenuation for an Object3D in THREE.js? I'm working on rendering a trajectory at a massive scale using arrow helpers to show the motion direction. I want the arrow heads to maintain their orientation without changing si ...

The selected value from a dropdown list may occasionally come back as text

I am facing an issue with a dropdown list on my form that has Integer Values set to display text. The problem arises when I run the code to show the value and associated text, as the text is being displayed as the value itself. Is there any workaround avai ...

Implement a Vue binding that applies an active class on click, replacing the previous one

I have a loop that dynamically adds div sections to the page. I want the first one to be selected on page load, and then when another one is clicked, it should become active while the previous one loses its active status. I attempted the code below but it ...

Should an HTML canvas in Angular be classified as a Component or a Service?

I have a basic drawing application that uses an MVC framework in TypeScript, and I am looking to migrate it to Angular. The current setup includes a Model for data handling, a View for rendering shapes on the canvas, and a Controller to manage interactio ...

Leverage information extracted from the Node.js function

As I dive into the world of NodeJS, a particular issue arose while working with the getCurrentWeather() function. It's asynchronous nature means that it loads instantly upon app start and writes data to variables. However, when attempting to use these ...

Verify that the computer is connected to the Internet by sending an ajax request to Google

Whenever I need to test my internet connection, I rely on the following code snippet: const checkInternetConnection = () => { $('input').ajaxError(function(){ alert("failed"); }); $.get('http://www.google.com', f ...

Error occurs while running NPM script

My current task involves updating the dependencies of a React application. One of the key scripts in this app is defined in the package.json file, which is responsible for generating a message bundle for each locale. "scripts": { "build:langs": "NODE_EN ...

Is it possible to conditionally define which keys are 'required' within a schema?

How can the 'required' field in a mongoose schema be conditionally set? For example: If x is true, then y's required field should also be true. Otherwise, y's required field should be false. ...

Ensuring Consistency in Object Size When Switching Between Perspective and Orthographic Cameras

Struggling to toggle between Perspective and Orthographic cameras in my script. I need objects at certain depths to maintain their projection size. I've reached a point of confusion when trying to understand the geometry... Can anyone recommend a sim ...

How to add an external JavaScript file to a nuxt.js webpage

Need some help with a simple query. I'm looking to incorporate this widget code from CodePen into my Nuxt.js project. The code works fine when using RAW HTML: <!DOCTYPE html> <html> <head></head> <body> <dev-widge ...