What is the best way to calculate the total sum of dynamically changing inputs in Angular 2?

Is there a way to calculate the total sum from dynamic inputs in angular 2? I'm not sure how to implement this. Thanks!

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

//html component
<md-input-container style="width: 80px;">
                <input md-input class="debit" formControlName="debit" [(ngModel)]="debit[i]">
              </md-input-container>

Answer №1

It appears that you are dynamically generating debit text and utilizing ngModel. To achieve this, consider the following approach:

(onChange) = "calculateTotal()" for each input-text representing a debit and apply [(ngModel)]="totalAmount" to the total input-text in your .ts file implement the following logic

calculateTotal(){
sum = 0;
for(data of debit){total = total + data;}
totalVal = total;
}

Answer №2

When working with reactive form control, all the form controls within the form tag have their values stored in the form instance. Here is an example:

<form [formGroup]="myForm">
            <input type="number" formControlName="value1"/>
            <input type="number" formControlName="value2"/>
</form>

To create the form, you can use the form builder class like this:

this.myForm = this.fb.group({
            value1: [5, Validators.required],
            value2: [2, Validators.required]
});

The form instance myForm will store the updated values of all the controls in the property myForm.value. In this case, it will contain { "value1": 2, "value2": 5 }. To calculate the total, you can use this property object to print the sum like so:

sum = Object.keys(this.myForm.value).reduce((prev, curr) => {
  return prev + this.myForm.value[curr]
}, 0);

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

The Facebook provider is missing in Ionic Native

An error has occurred: No provider for Facebook!     InjectionError (core.es5.js:1231)     NoProviderError (core.es5.js:1269)     ReflectiveInjector_ ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

Interacting with an iframe within the same domain

I'm currently working on an application in Angular 6 that requires communication with an iframe on the same origin. I'm exploring alternative methods to communicate with the iframe without relying on the global window object. Is there a more effi ...

Show a modal when the axios request is finished

EDIT: After some exploration, I've shared the solution I found in case it helps others facing a similar issue. I'm currently working on building a reusable Bootstrap 5 modal child component within Vue3. The goal is to pass an ID as a prop from t ...

Limiting the data types of array elements applies to variables, not to indexes

type Soccer = { ball: string } type Basketball = { jump: string } type Data = Soccer[] | Basketball[] if ('ball' in data[index]) { // type guard not effective here. <MyComponent something={data[index]} /> // data: Soccer[] | Basketball[] ...

Setting up Template-driven Form in Angular 7

I am searching for a solution to pre-populate specific form fields and then execute a function containing an if(this.form.valid) condition. Within the ngOnInit method, there is an API request that retrieves basic information and populates it within the fo ...

Steps to trigger pipe activation in Angular when the model is updated:1. Execute the

I have a unique filter pipe that allows me to filter an array of objects. This filter pipe has a dependency injection through a service. The service contains the model data filterService.data. Is there a way to activate this pipe in the template only when ...

"Ionic2 makes an HTTP POST request and then follows up with an

I've been attempting to post data using the Angular HTTP POST method as shown below. However, it seems to be executing the GET method instead. Any advice or guidance on this issue would be greatly appreciated. https://i.stack.imgur.com/IkSq3.png log ...

Developing applications with Angular 4, Spring Boot, Maven, and Eclipse requires frequent rebuilding to see code changes

I have been struggling to find a solution to my issue despite searching extensively on the internet. I am currently working on an application that combines Angular 4 with Spring Boot using STS (Eclipse) and Maven. Every time I make changes in Angular, I ha ...

Exploring methods for interacting with and controlling structural directives in e2e testing

Background: My goal is to permutation all potential configurations of an Angular2 screen for a specified route and capture screenshots using Protractor from the following link: http://www.protractortest.org/#/debugging. Problem: I am struggling to figure ...

Using the appropriate asynchronous action in Redux with the Redux-Thunk middleware

While learning middleware redux-thunk, I created a simple React App. However, I am facing a transpilation issue due to an incorrect type of async action fetchPosts in the interface PostListProps. Below is the code snippet of the functional component where ...

Consolidate various arrays of objects while eliminating duplicate items based on an optional property

Imagine having multiple arrays like these: const arr1 = [ { "id": "1", "type": "sales" }, { "id": "2", "type": "finance" } ] const arr2 = [ { "type": "s ...

Instead of displaying the name, HTML reveals the ID

I have defined a status enum with different values such as Draft, Publish, OnHold, and Completed. export enum status { Draft = 1, Publish = 2, OnHold = 3, Completed = 4 } In my TypeScript file, I set the courseStatus variable to have a de ...

Solving Issues with Names, Modules, and Other Strange Elements in Angular Universal

While the main app runs smoothly, attempting to serve the bundled SSR results in perplexing errors that I'm struggling to comprehend. All setup details are provided below for reference. The process of creating a server-side app seems riddled with sma ...

Demonstration of basic geometric shapes being generated using Forge Viewer Angular

Using the ng2-adsk-forge-viewer library in Angular 7, I am attempting to render a .dmg file within the browser and create a custom geometry on the view. After creating an Extension and adding the addToScene method, while the Extension runs successfully, I ...

Angular - Facing issues with CORS for every request made

Currently, I am developing an angular 12 application for my university with a java back-end. While testing Angular's http client, I encountered an issue where CORS is blocking my requests. const API_URL = 'http://localhost:9080' @Injectable ...

Issue with displaying data using a custom pure pipe and boolean in ngIf condition

For my current web project, I require a friendship/follow feature. There are two roles involved: admins and regular users. Regular users have the ability to follow other users, while admins do not possess this capability. When a user wishes to follow anot ...

What is the way to declare a prop as optional in Svelte using TypeScript?

I am facing an issue in declaring an optional prop in Svelte with TypeScript. The error message I receive is "Declaration or statement expected". Can someone guide me on how to correctly declare the prop? Definition of My Type: export enum MyVariants { ...

The global class variable encounters an error when trying to assign the value of "socket" to it

Within my class constructor, I am setting up a Socket connection and then storing the socket parameter in a global class variable (this.socket_variable = socket) so that I can access it across all functions in the class. CODE const { Server } = require(&q ...

Issue with TypeORM Many-to-Many relation returning incorrect data when using the "where" clause

I'm facing an issue with my database tables - User and Race. The relationship between them is set as Many to Many , where a Race can have multiple Users associated with it. My goal is to retrieve all the Races that a particular user is a member of. Ho ...