The expression has been altered following verification. It previously read as 'model: 1777' but now states 'model: 2222'

I've been working on this HTML code that utilizes [(ngModel)] to update input values, and I want the Total, Subtotal, and Amount Paid fields to be automatically calculated when a change is made. However, I'm encountering some issues with this approach.

  1. One of the problems I'm facing is that whenever new data is added, all existing data gets updated with the last entered value, which can be seen in the screenshot below:

    https://i.stack.imgur.com/s0qyU.png

I would greatly appreciate any assistance you can provide.

Here's my HTML code:

 <form [formGroup]="addsale" (ngSubmit)="onaddsale()">
      <table align="center" class="table table-bordered table-hover">
        <thead>
          <tr style="color:black;">
            <th>Unit_price</th>
            <th>Quantity</th>
            <th>Description</th>
            <th>Subtotal</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr class="group" style="cursor: pointer" *ngFor="let item of products; let i = index">
             <td>
              <input formControlName="Unit_price" id="Unit_price " type="number" class="validate"[(ngModel)]="item.Unit_price">
            </td>
            <td>
              <input formControlName="Quantity" id="Quantity " type="number" class="validate"  [(ngModel)]="item.Quantity"> 
            </td>
            <td>
              <input type="text" formControlName="Description" id="Description" name="Description" [(ngModel)]="item.Description">
            </td>
            <td>
              <input formControlName="Subtotal" id="Subtotal" type="number" class="validate"  [(ngModel)]="item.Subtotal">
            </td>
            <td>
              <button type="button" class="fa" (click)="onDelete(i)">x</button>
            </td>
          </tr>
        </tbody>
      </table>
      <br>
      <br>
      <div class="row">
        <div class="input-field col s2" style="float: right;">
          <label for="total">Total {{total}} ALL</label>
          <input formControlName="total" id="total" type="text" class="validate"   [(ngModel)]="total">
        </div>
        <div class="input-field col s2" style="float: right;">
          <label for="amount_paid">Amount Paid:</label>
          <input formControlName="amount_paid" id="amount_paid" [(ngModel)]="total" type="text" class="validate">
        </div>
        <div class="input-field col s2" style="float: right;">
          <label for="total">Subtotal</label>
          <input formControlName="Subtotal" id="Subtotal" type="text" class="validate"  [(ngModel)]="total">
        </div>
      </div>

      <hr>
      <br>
      <div id="add_homebox_button_container" class="row" style="float: right;">
        <button id="add_client_button" type="submit" class="btn waves-effect waves-light">
          Register
        </button>
      </div>
    </form>

TS Code:

export class AddSaleFormComponent implements OnInit {
  addsale: FormGroup;
  loading: boolean = false;
  client: Client[];
  producttype: ProductType[];
.
.
.

}

Answer №1

The issue lies in the way your form is structured with the FormGroup. Currently, you have a single FormControl for 'Unit_price' which multiple rows in your template are trying to reference using the FormControlName directive. This causes confusion because all these inputs point to the same FormControl, creating unexpected behavior. It's not valid to have duplicate controls under one FormGroup.

To resolve this, you need to create a separate FormGroup for each row in your table. By doing this, each row will have its own unique FormControl within its respective FormGroup, eliminating the issues you're facing.

This means that you should create individual FormGroup instances for each product in the products array, and possibly another FormGroup for shared controls like total and subtotal.

You can also consider removing data binding from the 'total' fields if they aren't meant to be edited. Simply switch from [(ngModel)] to [ngModel] for those fields.

In general, when using FormControl and FormGroup in reactive forms, there may be no need for ngModel at all.

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

Issue with dynamic imports and lazy-loading module loadChildren in Jhipster on Angular 8, not functioning as expected

When utilizing dynamic import, it is necessary to modify the tsconfig.json file in order to specify the target module as esnext. ./src/main/webapp/app/app-routing.module.ts 14:40 Module parse failed: Unexpected token (14:40) File was processed with these ...

The Value Entered in Angular is Unsaved

I have encountered an issue with my app's table functionality. The user can enter information into an input field and save it, but upon refreshing the page, the field appears empty as if no data was entered. Can someone please review my code snippet b ...

JQuery HTML form validation continues to send emails even when there are blank entries

I've set up an HTML form with three required fields, and I'm trying to prevent the form from submitting an AJAX call if those fields are left empty. $("#contact").submit(function(e){ e.preventDefault(); var ajaxurl = '<?php echo ...

Issue with ADFS 2016 oAuth: Users not being redirected to login page post logout

Having an issue with ADFS 2016 and my Angular application using ng2-adal js for authentication and authorization. After users logout, they are not redirected back to the login page. Debug traces in Event Viewer show the following error: Error: OAuthSignou ...

Creating a OneToMany relationship in NestJS entity model

In my current project with NestJS, I am working on defining entity fields. While I have successfully defined a ManyToOne relation, I am facing difficulties in setting up the syntax for a OneToMany relation to match the structure of my other relationships. ...

Verify the legitimacy of the object

I'm encountering an issue while attempting to create a function that verifies the validity of an object. const isPeriodValid = (period: Period | null): boolean => { return period && period.start && period.end; } export interfac ...

The issue of template referencing not working occurs when the original source contains a *ngIf condition

<mat-icon #suggestionIcon="cdkOverlayOrigin" class="suggestionIcon" *ngIf="part.highlight" (click)="openOverlay()" cdkOverlayOrigin > add_circle </mat-icon> <ng-template #myTemplate * ...

Visual Studio Code encountering an NPM error

I am encountering errors when I try to run Visual Studio. The specific errors are: npm ERR! code ENOENT npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'F:\AngularNew\package.json' ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

Is SignalR affected by the CORS same-origin policy?

After enabling CORS in my .NET core app, regular http requests are functioning properly. However, I am encountering CORS issues with SignalR when running my Angular app. Any suggestions or solutions would be greatly appreciated. Thank you in advance. Cros ...

Using Angular 4 with Firebase to display nested objects within an object

My Firebase data: { "hotel" : { "-Kjgyamcup6ULm0Awa-1" : { "complete" : "true", "images" : { "-Kjgyb6A2gRiDhwaWx-V" : { "name" : "2.jpg", "url" : "https://firebasestorage.googleapi ...

I encountered an error while trying to globally install @ionic/cli using the npm command. The error message displayed was

I am currently trying to set up Ionic 6 on my system. So far, I have installed various versions of npm using nvm. nvm ls D:\<user_name>\Projects\Ionic-6>nvm ls * 16.14.2 (Currently using 64-bit executable) 16.14.0 16.13. ...

AngularDart's runtimeType object

My component is designed to accept a model object, but the type of this object determines which specific component will be rendered inside: <div [ngSwitch]="poolModel.runtimeType.toString()"> <template ngSwitchCase="CryptonoteMiningPool">& ...

I am hoping to refresh my data every three seconds without relying on the react-apollo refetch function

I am currently working with React Apollo. I have a progress bar component and I need to update the user's percent value every 3 seconds without relying on Apollo's refetch method. import {useInterval} from 'beautiful-react-hooks'; cons ...

What is the process for crafting a Vuejs controlled input form?

Although I am familiar with creating controlled components in React using state, I am new to the Vue framework and would like to understand how to adapt my code from React to be compatible with Vue. My goal is to store the values of input fields in a data ...

Definition for TypeScript for an individual JavaScript document

I am currently attempting to integrate an Ionic2 app within a Movilizer HTML5 view. To facilitate communication between the Movilizer container client and the Ionic2 app, it is crucial to incorporate a plugins/Movilizer.js file. The functionality of this f ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Creating Angular models for complex nested JSON structures

I'm a beginner with Angular and I'm dealing with nested API responses from a Strapi application. I've set up a model using interfaces, but I'm having trouble accessing attributes from the product model when trying to access product data ...

Ways to assign a boolean value to HTML using Angular?

Can someone help me set the initial value of showProduct to false for the app-product HTML selector? showProduct:boolean = false; <button (click)="showProduct=!showProduct">Show Product</button> <div *ngIf="!showProduct"> <app-p ...

Issue encountered with Firebase JS SDK: firebase.d.ts file is missing which leads to a Typescript error when trying to

I'm currently working on an Ionic project with AngularFire. I encountered a typescript error when trying to run ionic cordova build --prod --release android. typescript error '/home/sebinbenjamin/workspace/myapp/node_modules/firebase/firebase. ...