Updating input values in Angular reactive forms

I have a repeated table row that includes a form. I need to dynamically update the total field based on the price and quantity in my reactive forms setup. Here is the code snippet:

<tbody formArrayName="products">
    <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i">
      <th scope="row">{{i+1}}</th>
      <td><input type="text" class="form-control" placeholder="Product Code" formControlName="product_code"></td>
      <td><input type="text" class="form-control" placeholder="Product Name" formControlName="product_name"></td>
      <td><input type="number" class="form-control" placeholder="Price" formControlName="product_price"></td>
      <td><input type="number" class="form-control" placeholder="Quantity" formControlName="product_quantity"></td>
      <td><input type="number" class="form-control"  formControlName="total" disabled></td>
      <td><button type="button" class="btn btn-danger ml-2" (click)="deleteProduct(i)">Remove</button></td>
    </tr>
  </tbody>

Is there a way to automatically calculate the total value when entering the Price and Quantity? Here's the TypeScript logic:

ngOnInit() {
this.myForm = this.fb.group({
  customer_name: '',
  customer_phone: '',
  customer_address: '',
  products: this.fb.array([0])
});
}
get productForms() {
return this.myForm.get('products') as FormArray;
}
addProduct() {
    const product = this.fb.group({
      product_code: [],
      product_name: [],
      product_price: [],
      product_quantity: [],
      total: []
    });

    this.productForms.push(product);
  }

Answer №1

If you're looking to optimize your code, try utilizing template variables in the following manner

<td><input type="number" class="form-control" placeholder="Price" formControlName="product_price" #price></td>
<td><input type="number" class="form-control" placeholder="Quantity" formControlName="product_quantity" #quantity></td>
<td><input type="number" class="form-control"  [value]="(price.value || 0) * (quantity.value || 0)" disabled></td>

Calculate the total amount for all products

component

getProductsTotalPrice() : number { 
   let total = 0;
   for(let product of  productForms.controls){
     total += (+product.get('price').value || 0) * (+product.get('quantity').value || 0)
   }
    return total;
  }

template

 <span>{{getProductsTotalPrice}}</span>

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: Unable to find suitable routes for navigation. URL Segment: 'profile' or Encounter: Server could not load resource as response status is 401 (Unauthorized)

Currently, I am working on the MEANAUTH application and encountering an issue with accessing user profiles using angular jwt. When attempting to log in and access user profiles at https://localhost:3000/profile, I receive the following error message: Faile ...

Middleware fails to execute on routing in Nextjs 13.4 application

Something's not quite right. I can't seem to get my middleware to run... Here's the code I'm using: export const config = { matcher: '/api/:function*', }; I specified this config so that it would run only when there's ...

Issues have arisen where the modal popup in Bootstrap and Angular is failing to appear

Displayed below is a table with a modal popup created using bootstrap 4 within an angular environment. <tbody *ngFor="let data of json | sizeFilter : sizeInput"> <tr> <td (click)="onUpdateClick(data.hash , data. ...

The karma test appears as "passed" in IntelliJ, even though there are remaining errors present, leading to a failure in the CI/CD process

Currently working on an Angular project, my goal is to ensure all tests turn green. Surprisingly, they all passed on my end, but the CI/CD process (Teamcity) failed. Upon checking the log in my IntelliJ IDE, it was revealed that certain tests actually repo ...

Unable to compile because error TS1039 prohibits initializers in ambient contexts

Upon updating my global Angular CLI to the latest version, I encountered an error. After some research, it seems that the issue may be related to my local CLI version (1.5.0) not being utilized for some reason. I am now unable to build the project due to t ...

Vuetify's v-data-table is experiencing issues with displaying :headers and :items

I'm facing an issue while working on a Vue project with typescript. The v-data-table component in my Schedule.vue file is not rendering as expected. Instead, all I can see is the image below: https://i.sstatic.net/AvjwA.png Despite searching extensi ...

Text not displaying in Angular Select when both *ngFor and *ngIf are combined

My challenge involves a form with 4 select inputs. The goal is to ensure that once a value is selected in one input, it should not appear in the other select inputs. I managed to create a functional solution, however, there's an issue where the select ...

How should one properly assign an element type provided as an argument?

I'm attempting to define a type for an element passed as a parameter using React.ComponentType. import * as React from "react" type BaseType = { element: React.ComponentType } const Base = ({element: Element}: BaseType) => ( <Ele ...

Unable to access API hosted on localhost from Angular Client integrated with C# Backend running on a standalone server unit

I have an Angular Client (v14) and a .Net 6 WebAPI running on separate projects within a Raspberry Pi. The setup is for a standalone kiosk where both the front end and backend are hosted on the same device. My goal is to access the front end from a PC on ...

What could be the reason for a "Delay" in the state update process within Redux?

I'm currently facing some issues with the Redux and React Native code provided below. The goal is to build a workout tracking application where users can input their progress. I've implemented a 'workoutSessionSlice' to manage the stat ...

Tips for creating a script that waits for a specific amount of time before moving on to the next execution block in Protractor

Need to automate a test case that involves filling out a form with 5 date pickers and 30 fields. Once the form is filled, a jar needs to be invoked to retrieve the data from the DB and process it independently. Note: The jar does not send any value back t ...

Error 404 encountered when updating packages in Angular2 tutorial: platform-browser-dynamic.umd.js

I recently started following an Angular2 tutorial, but upon returning to it and reaching the Routing chapter, I realized that the tutorial had been slightly updated. This required me to go back and update the package.json file to match the current version, ...

Addressing the reactivity issue when incorporating basic markdown directive into vuejs

In an effort to reduce dependency on vue-i18n formatting, I decided to create a simple Markdown formatter directive that only implements bold, emphasize, and strike-through styles. The current implementation of the directive is as follows: import _Vue ...

Managing two subscriptions based on conditions in Angular

I'm currently working on a component that includes the following code snippet: this.service().subscribe((result) => { this.service2(result).subscribe((result2) => //other code }} As I strive to follow best practices in Angular development, I&ap ...

Restricting the number of mat-chips in Angular and preventing the input from being disabled

Here is my recreation of a small portion of my project on StackBlitz. I am encountering 4 issues in this snippet: I aim to restrict the user to only one mat-chip. I attempted using [disabled]="selectedOption >=1", but I do not want to disable ...

What is the method to empty input fields after data has been submitted in an Angular application?

    I'm facing a challenge with my web form. I have a dropdown menu using mat-select and an input field. When I click the submit button, the data is sent. However, I want the input field to clear after submission without affecting the mat-select dr ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

Issues with anchor tag click event in Firefox browser not functioning as expected

I have encountered an issue while trying to create an anchor tag in a TypeScript file. When clicking on this button, the anchor tag should be created. This functionality is working correctly in Chrome and IE, however, it seems to be not working in Firefo ...

What is the solution to the error message "Unable to assign property of undefined"?

I am currently working on an angular countdown timer and encountering a TypeError when attempting to access a variable from another component. I am struggling to identify the root cause of this issue. Here is the video tutorial that I am using as a referen ...

Removing outlines on <p> <a> or <div> elements with Ionic and Angular seems to be a challenging task

Hey there, I’m currently working on my application which includes a login page. I've implemented a “Forgotten password ?” link, but no matter what I try, like using .class and :focus {outline: none}, I still see a yellow square around the item. ...