Whenever I try to input a value, it doesn't get submitted properly after making a change

For my current project, I am working on generating an invoice. I have implemented a function called get subtotal(){} to calculate the total value of the invoice, and it is functioning correctly. However, I encountered an issue where I need to apply a discount from 100 to 90 to the subtotal.

I attempted to modify the code but it did not produce the desired result. Could you please provide me with suggestions on how to resolve this problem? Here is the HTML code:

<div class="input-field col s2" style="float: right;">
      <input formControlName="Subtotal " id="Subtotal " [value]="subtotal " type="number" class="validate" (change)="updateForm($event)">
    </div>

And here is the TypeScript code:

  updateForm(event) {
    console.log(event)
    let updatedAmount = event.target.value
     this.addsale['controls']['Subtotal '].setValue(updatedAmount );
   }
  onaddsale() {
    let sale = this.addsale.value;
    sale.Subtotal = this.subtotal;
    let newSale = new Sale(sale);
    console.log(newSale)}

 get subtotal() {
    return this.products
      .map(p => p.p_Unit_price * p.p_Quantity)
      .reduce((a, b) => a + b, 0);
  }

Thank you for your assistance!

Update:

this.addsale = this.formbuilder.group({
      'Subtotal ': new FormControl('', Validators.required),
      'products': this.formbuilder.array([]),
    });

Answer №1

Instead of passing values back and forth in the view (HTML), simply set the value of the control if you need a precalculated value in there.

Start by building your form with the form builder.

Afterward, update the subtotal by using

this.addSale.controls.Subtotal.setValue(this.subtotal)
. Make sure to do this whenever the subtotal changes.

ngOnInit() {
  this.service.productList.subscribe(productList => {
    this.products = productList;
    this.addsale.controls.Subtotal.setValue(this.subtotal)
  });
}

Avoid using sale.Subtotal = this.subtotal.

let sale = this.addsale.value already takes care of that.

In your view, utilize basic reactive form binding.

 <input formControlName="Subtotal" id="Subtotal" type="number" class="validate">

Your value should automatically update each time you call setValue(this.subtotal).

The user can override the value if necessary. However, it might get overwritten when more products are added. To prevent this, monitor whether the user has changed the value and stop updating it with the new subtotal.

Check out this working demo based on the demo provided in the comments.

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

Next.js is faced with a frustrating issue where images and videos are failing to display

I've been working on my Next.js 13 project with TypeScript, eslint, and Chakra UI, but I'm facing an issue with images and videos not displaying. Despite trying both the HTML <img> tag and importing Image from Chakra, the problem still per ...

Removing a particular item from an Observable of arrays containing any type

My application has an Observable that contains an array of places: places: Observable<Array<any>>; In the template, I am using the async pipe to iterate over the array: <tr *ngFor="let place of places | async"> ... </tr> After ...

When including a JSON file, Angular 8 does not recognize the rootDir

After including a JSON file in my library, I encountered an error during the build process stating that the my.json file is not located under rootDir. ...

Utilizing a custom class to perform an HTTP POST request in Angular/TypeScript by implementing the `toString()` method

When working with Angular Reactive forms, I encountered an issue while sending the form.value data to an asp.net web-api. The code snippet includes a custom class called len, which emulates a simplified version of a TimeSpan. Here is an example of my requ ...

Visualizing data from an array within a different Vue component: A step-by-step guide

In my Vue app, I have successfully sent an array from one component to another. However, I am now facing a challenge in visually displaying this data. The issue arises when trying to extract and display specific values, like the date itself. Despite being ...

Easiest Angular Carousel Solution

My goal is to create a basic Angular Carousel to enhance my understanding of Angular. While I have received helpful answers in the past, I am seeking further clarification to deepen my knowledge of Angular2+ and Typescript. Here's what I have so far: ...

Scrollbar is always visible on Angular Flex Layout

As someone who is just starting to work with Angular and flex layout, I have a simple page setup consisting of a header with a side navbar and router outlet. I encountered an issue where my page always displays a scrollbar. If I remove fxFlexFill, the sc ...

DuplicateModelError: Unable to duplicate model after it has been compiled, React.js, MongoDB, TypeScript

In the early stages of developing an application using Next.js, Mongoose, and Typescript, I encountered a persistent issue. Whenever I attempt to send a request through Postman after clicking save, it fails, displaying the error message: OverwriteModelErr ...

Guide on how to conditionally display a button or link in a Next.js Component using TypeScript

Encountering a frustrating issue with multiple typescript errors while attempting to conditionally render the Next.js Link component or a button element. If the href prop is passed, the intention is to render the Next.js built-in Link component; otherwise, ...

When onSubmit is triggered, FormData is accessible. But when trying to pass it to the server action, it sometimes ends up as null

I am currently utilizing NextJS version 14 along with Supabase. Within my codebase, I have a reusable component that I frequently utilize: import { useState } from 'react'; interface MyInputProps { label: string; name: string; value: stri ...

Error in Redirecting to Localhost

Recently, I developed an Angular App that interacts with the MS Graph API using MSAL. Initially, everything worked smoothly when running "ng serve" in Angular CLI. However, I encountered a problem when I packaged this Angular App with electron to deploy i ...

Angular - The 'options' property is not found in the 'HTMLOptionElement' type

Currently, I am attempting to modify the choices in a dropdown menu based on the selection made from another dropdown. This problem led me to come across a helpful resource on a website called "Form Select Change Dynamic List Option Elements Tutorial". How ...

Efficiently utilizing ngrx by orchestrating various services and actions to achieve accurate mapping

Combining multiple effects into one is my current goal due to an issue with dispatching actions separately. The aim is to execute sequentially after verifying the value returned from the first service call. Here are the three separate effects I have: @Eff ...

Components in Ionic used in app.component.ts and various pages

Struggling with integrating a custom component in Ionic. In my app.html, I have a menu and I'm using lazy-loading for the pages. I am trying to include the component in both the menu in app.html and on some pages. However, I'm facing an issue ...

Angular: Implementing ngIf within ngFor for Dynamic Content Display

I'm working on dynamically populating a list with conditional rendering for each list item, where the condition can be changed by user input. For instance: app.component.ts private check = true; private some = [ {name: 'ABC', cond ...

Unable to locate the control with the name "email" or "pwd", and the onSubmit function is not defined

I am currently facing an issue with form validation using reactive forms. The problem seems to be related to the console errors indicating that it cannot find controls named 'email' and 'pwd'. This is a basic sign-in form, and here is t ...

Implementing a scroll-triggered class addition in Angular

I am currently refreshing my knowledge of Angular. After installing AngularCLI, I am attempting to transition from using jQuery to add a class on scroll. Would it be necessary to utilize [ngClass] in order to check a variable with window location? Right ...

Data in JSON format for Ionic OneSignal

This is my duyurular.ts file ; export class DuyurularPage { duyurular: any; constructor(public navCtrl: NavController, public navParams: NavParams, public loadingPage: LoadingController, platform: Platform, statusBar: StatusBar, splashScreen: Splas ...

What is the best way to establish communication between the browser and an express.js server while utilizing angular ssr?

I've encountered a server-side rendering (SSR) issue that does not seem to be addressed in either the Angular documentation or the new Angular developer documentation. My inquiry pertains to transferring data from the browser to the server, as oppose ...

Creating a Dynamic Download Link in Angular 6

Hello everyone, I need assistance in making my download feature dynamic. Here is my HTML code: <button class="btn btn-primary" (click)="downloadMyFile({{account.students[0].schoolId}})"><i class="fa fa-file-pdf-o"></i> Download</butt ...