Calculate the total by subtracting values, then store and send the data in

Help needed with adding negative numbers in an array. When trying to add or subtract, no value is displayed. The problem seems to arise when using array methods. I am new to arrays, could someone please point out where my code is incorrect? Here is my demo code on StackBlitz.

HTML

<div class="p-buttom">
    <ion-button expand="full" color="dark" (click)="add()">Add</ion-button>
</div>
    <div class="size-bg" *ngFor="let num of size;let i = index">
    <span style="display: flex;">
        <ion-col>
            <ion-item lines="none" size="6" class="border">
                <ion-label position="stacked">weight</ion-label>
        <ion-input type="text" class="uppercase" [(ngModel)]="data.weight[i]" name="menuCode"></ion-input>
            </ion-item>
        </ion-col>
        <ion-col>
            <ion-item lines="none" size="6" class="border">
                <ion-label position="stacked">Price</ion-label>
        <ion-input type="text" class="uppercase" [(ngModel)]="data.price[i]" name="menuCode"></ion-input>
            </ion-item>
        </ion-col>
    </span>
    <ion-label style="color: black; ">quantity</ion-label>
    <ion-col size="12">
        <div class="add-quatity">
            <ion-button class="removeBtn no-padding " fill="solid " slot="end" style="color: black;" (click)="MinusMinOrder() ">
               -
            </ion-button>
            <ion-input class="itemCount no-padding" name="quantity" (keypress)="numberOnlyValidation($event)" [(ngModel)]="data.quantity[i]" value="{{addQuantityP[i]}}"></ion-input>
            <ion-button class="addBtn no-padding " fill="solid " slot="end" style="color: black;" (click)="addQuantity(i) ">
                +
            </ion-button>
        </div>
    </ion-col>
    <div>
        <ion-button expand="full" color="danger" *ngIf="i >0" (click)="remove(i)">Delete</ion-button>
    </div>
    </div>
<div>
  <ion-button fill="solid " slot="end" (click)="addMenu() ">Submit</ion-button> 
</div>

Component

add(){
    this.size.push('');
  }

  remove(index) {
    this.size.splice(index,1)
  }
  minusQuantity(i){
    console.log(i);
    this.data.quantity[i]--;
    console.log(this.data.quantity[i]--);
  }
  addQuantity(i){
    console.log(i);
    this.data.quantity[i]++;
    console.log(this.data.quantity[i]++);
  }
addMenu(){
  console.log(this.data);
}

Thanks in advance

Answer №1

I have identified the issue in your code. To dynamically create an array, you need to initialize default values for the array of objects.

For example:

size = [];

This is the resulting array that needs to be finalized. Your UI data contains objects with certain properties.

For instance:

{ weight: 0,
  quantity: 0,
  price: 0,
 }

Now that your object is ready, it can be pushed into the size array.

When you click on the

add() {
 this.size.push({ weight: 0,
  quantity: 0,
  price: 0,
 });
}

function, simply push this object each time. In Angular UI, a new object with new values will be created without the need for any complex logic.

I am offering you a comprehensive solution where you can add multiple items simultaneously and test it out. If you require further assistance from my end, please do not hesitate to reach out. Thank you!

Here is the link to access the solution.

Cheers!

Answer №2

There are a few issues with your code:

  1. The way you're collecting the data won't work when adding nested rows.
  2. The method name for subtracting quantity is incorrect.
  3. You included
    [(ngModel)]="data.quantity[i]"
    unnecessarily since there's no two-way binding in use.

I've made some corrections to your code and noted the changes with comments. You can review them on Stackblitz

import {
  Component
} from '@angular/core';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
  size = [];
  // Changing the data structure to map nested rows
  data = [{
    weight: 0,
    price: 0,
    quantity: 0
  }]

  constructor() {}

  add() {
    this.size.push('');
  }

  remove(index) {
    this.size.splice(index, 1)
  }

  minusQuantity(i) {
    // Stop reducing quantity below zero
    this.data[i].quantity = this.data[i].quantity != 0 ? this.data[i].quantity - 1 : 0
  }

  addQuantity(i) {
    this.data[i].quantity = this.data[i].quantity + 1
  }
  addMenu() {
    console.log(this.data);
  }
}
<ion-header>
  <ion-toolbar>
    <ion-title>
      My app
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
   <div class="p-buttom">
        <ion-button expand="full" color="dark" (click)="add()">Add</ion-button>
    </div>
        <div class="size-bg" *ngFor="let num of size;let i = index">
        <span style="display: flex;">
            <ion-col>
                <ion-item lines="none" size="6" class="border">
                    <ion-label position="stacked">weight</ion-label>
            <ion-input type="text" class="uppercase" [(ngModel)]="data[i].weight" name="menuCode"></ion-input>
                </ion-item>
            </ion-col>
            <ion-col>
                <ion-item lines="none" size="6" class="border">
                    <ion-label position="stacked">Price</ion-label>
            <ion-input type="text" class="uppercase" [(ngModel)]="data[i].price" name="menuCode"></ion-input>
                </ion-item>
            </ion-col>
        </span>
        <ion-label style="color: black; ">quantity</ion-label>
        <ion-col size="12">
            <div class="add-quatity">
                <ion-button class="removeBtn no-padding " fill="solid " slot="end" style="color: black;" (click)="minusQuantity(i) ">
                   -
                </ion-button>
                <ion-input class="itemCount no-padding" name="quantity" (keypress)="numberOnlyValidation($event)" value="{{data[i].quantity}}"></ion-input>
                <ion-button class="addBtn no-padding " fill="solid " slot="end" style="color: black;" (click)="addQuantity(i) ">
                    +
                </ion-button>
            </div>
        </ion-col>
        <div>
            <ion-button expand="full" color="danger" *ngIf="i >0" (click)="remove(i)">Delete</ion-button>
        </div>
        </div>
    <div>
      <ion-button fill="solid " slot="end" (click)="addMenu() ">Submit</ion-button> 
    </div>
</ion-content>

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

When attempting to access Firebase Storage with Angular, you may encounter the error message: "TypeError: app.storage

Having trouble connecting my Angular app to FireBase. The component appears blank and the Chrome console is showing a 'TypeError: app.storage is not a function'. Any ideas on what I might be doing wrong? Thanks in advance. ng --version Angular C ...

Encountering TS2344 error when referring to the Component Ref in Vue.js during typing operations

I received a component reference on my FormCheckbox component from a patternlib. When I tried to incorporate the component into my own TestComp component, I encountered this TypeScript error that left me puzzled: TS2344: Type '{ name: string; mixins: ...

Convert parameterized lambdas for success and failure into an observable using RxJS

There is a function exported by a library that I am currently using: export function read( urlOrRequest: any, success?: (data: any, response: any) => void, error?: (error: Object) => void, handler?: Handler, httpClient?: Object, ...

Challenge encountered with implementing Next-Auth's authorize function in TypeScript

Encountering a type error in the authorize function while using NextAuth with CredentialsProvider export const authOptions : NextAuthOptions ={ session : { strategy: "jwt" }, providers : [ CredentialsProvider({ async authorize( c ...

Issue with ng2-charts not rendering properly on the client side when utilized in Angular version 2.0.0-beta-17

Struggling with using ng2-charts in my Angular 2 app and encountering some challenges. app.ts import {Component} from 'angular2/core'; import {CHART_DIRECTIVES} from 'ng2-charts/ng2-charts'; @Component({ selector: & ...

Setting up an empty array as a field in Prisma initially will not function as intended

In my current project using React Typescript Next and prisma, I encountered an issue while trying to create a user with an initially empty array for the playlists field. Even though there were no errors shown, upon refreshing the database (mongodb), the pl ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

Utilizing a created OpenAPI client within a React application

Using the command openapi-generator-cli generate -i https://linktomybackendswagger/swagger.json -g typescript-axios -o src/components/api --additional-properties=supportsES6=true, I have successfully generated my API client. However, despite having all th ...

Finding the file path to a module in a NextJS application has proven to be a challenge when utilizing the module

Currently, I am utilizing the webpack plugin module-federation/nextjs-mf, which enables us to work with a micro-frontend architecture. Based on the official documentation and referencing this particular example, it is possible to share components between ...

Mastering the proper usage of the import statement - a guide to seamless integration

I'm excited to experiment with the npm package called camera-capture, which allows me to capture videos from my webcam. As someone who is new to both npm and typescript, I'm a bit unsure about how to properly test it. Here's what I've ...

essential elements for mapping an array using typescript

Struggling to iterate through an array of objects, each with a unique id created by uuidv4(), resulting in a string type. TypeScript is giving errors (( Type 'String' is not assignable to type 'Key | null | undefined')) due to the &apos ...

Apply a spread of nested elements onto another spread

I am working with an array containing last names of Persons and need to populate new entries. However, I only have the last names and not the full Person objects. How can I address this issue? type Person = { name: string, lastName: string, age: ...

Changing the target in tsconfig.json to "es2022" leads to the error message "Property 'xx' is referenced before its initialization.ts(2729)"

My Angular code is filled with instances where I assign a property at its definition like this... public data$ = this.service$.fetchData; constructor(private service$: MyService However, after updating my tsconfig.json target to "es2022", I encountered ...

Establish a connection between two pre-existing tables by utilizing the Sequelize framework

I have two tables already set up (User and PaymentPlan), but they were not initially linked together. PaymentPlan.ts import { DataTypes, Model } from "sequelize"; import { sequelize } from "./DBConnections/SequelizeNewConnection"; exp ...

Creating QR codes from raw byte data in TypeScript and Angular

I have developed a basic web application that fetches codes from an endpoint and generates a key, which is then used to create a QR Code. The key is in the form of an Uint8Array that needs to be converted into a QR Code. I am utilizing the angularx-qrcode ...

Unit testing in Typescript often involves the practice of mocking

One challenge with mocking in Typescript arises when dealing with complex objects, as is the case with any strongly-typed language. Sometimes additional elements need to be mocked just to ensure code compilation, such as using AutoFixture in C#. In contras ...

The Date object in Typescript is represented as a string

My typescript interface includes a variable called start, which is typed as Date | null. This data is retrieved from a dotnet API that returns a DateTime object. The issue arises when the start variable is passed through a function in Date-fns, causing a R ...

Angular 2 Dropdown Multiselect Plugin - Fully Customize Width to 100%

Currently working on integrating the angular-2-dropdown-multiselect component: https://www.npmjs.com/package/angular-2-dropdown-multiselect The component functions correctly, but I am looking to adjust its width to fit the container... I believe simply ...

Creating dynamic HTML with Angular 2 using property binding

After retrieving an HTML string from the database, I came across html='<span>{{name}}</span>' where 'name' is a component property. I am looking to display this string in HTML while maintaining the name binding. I have expl ...

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...