Tips for calculating the total of keyup elements in an Angular application

There are "N" inputs in a formgroup that need to be summed:

<input (keyup)="sum($event)" type="text" name="estoque_variacao{{i}}" class="form-control" id="estoque_variacao{{i}}" formControlName="estoque_variacao">

This is the Typescript code:

sum(value){
    let sum;
    if(sum == null){
      sum = 0;
    }
    sum =  +Number(value.key);
}

When pressing "22", only "2" is obtained:

2.

Attempts have been made with this code:

sum += parseFloat(valor.key);

However, the same response is received.

How can this be achieved?

Something like this is needed, but in Angular/Typescript:

http://jsfiddle.net/35At5/

Answer №1

Your current code implementation can only handle one control, but you need to sum up values from all dynamically generated controls.

Follow these steps:

1. Update ts file

Create an object to hold all the control models.

public controls = {};

2. Update your html

<input [(ngModel)]="controls[i]" (keyup)="sum($event)" type="text" name="control{{i}}" class="form-control" id="control{{i}}" formControlName="control">

The ngModel directive will add properties to the controls object

3. Calculate the total sum

To calculate the sum of all control values, use this code snippet:

 let sum = 0;
 Object.keys(this.controls).map(key => {
   sum +=  +this.controls[key];
 });
 console.log(sum);

That's it!

Answer №2

When you trigger the keyup event, it only captures the most recent input without any reference to previous actions. To obtain the values from all form controls, you can utilize the formControl.value() method and aggregate the inputs from each of your form elements.

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

Error involving key mismatch between TypeScript inherited interface and literal string type

There are 3 interfaces (A, B, and C) that all extend from a shared interface (Common). Additionally, there is a container type which holds arrays of these 3 interfaces (Container). The goal is to select one of the arrays and extract a common property from ...

Retrieve highlighted text along with its corresponding tag in ReactJS

my <span class="highlight">highlighted</span> word The text above is showing an example including HTML tags. However, when using window.getSelection(), only the text "my highlighted word" is returned without the surrounding <span& ...

Transferring information between components, specifically when one of them is a routerOutlet within an Angular application

I need to transfer data from the category component to the product component within the dashboard component. However, I am facing an issue due to the presence of a router outlet inside the product component. View Dashboard Screen dashboard.component.html ...

The AngularJS2 component fails to render properly following the implementation of a new router

I recently encountered an issue with my AngularJS2 app component not loading after adding the router. Surprisingly, there was no error in the log. However, upon removing the router, the app started working again. Has anyone else faced a similar issue befor ...

Tips for implementing a real-time search feature in Angular

I require assistance. I am attempting to perform a live search using the following code: when text is entered into an input, I want my targetListOptions array, which is used in a select dropdown, to update accordingly. The code runs without errors, but not ...

Angular 6: Issue with displaying data on the user interface

Hello! I am attempting to fetch and display a single data entry by ID from an API. Here is the current setup: API GET Method: app.get('/movies/:id', (req, res) => { const id = req.params.id; request('https://api.themoviedb.org/ ...

Utilizing aria-role in Material UI's <Icon> component for enhanced accessibility

I've been using Material UI's <Icon /> component and came across a reference in their documentation about being able to use role="img", which is mentioned here: https://material-ui.com/components/icons/#semantic-svg-icons. However ...

I am looking to fetch a zip file within the MEAN stack framework

Here is frontend code (Angular):- download(user) { this.clientAPI.get(Endpoints.DOWNLOAD).toPromise() .then(res => { let blob = new Blob([new Uint8Array(res.file)], { type: 'application/zip' }); console.l ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...

When working with Angular 5, the question arises: how and where to handle type conversion between form field values (typically strings) and model properties (such

As a newcomer to Angular, I am struggling with converting types between form field values (which are always strings) and typed model properties. In the following component, my goal is to double a number inputted by the user. The result will be displayed i ...

Acquire key for object generated post push operation (using Angular with Firebase)

I'm running into some difficulties grasping the ins and outs of utilizing Firebase. I crafted a function to upload some data into my firebase database. My main concern is obtaining the Key that is generated after I successfully push the data into the ...

What is the best way to incorporate master/detail components without relying on hierarchical routes?

I need to combine the following elements. An index page with the route /items (plural). This page should be scrollable. When clicking on individual items, I want to display a detail page with the route /item/:id (singular). The detail page should have a ...

Implementing Reddit API with Single Page Application using Implicit Grant flow strategy

Whenever I try to redirect to https://www.reddit.com/api/v1/authorize?response_type=token&client_id=3JTVJFUn28MxFQ&state=RANDOMSTATEFORCONFIRMATION&redirect_uri=http%3A%2F%2Flocalhost%3A4200&scope=read from my Angular application, I encou ...

Broaden your interfaces by implementing multiple interfaces with Zod

Utilizing typescript, I am able to incorporate multiple interfaces interface Name { name: string } interface Age { age: number } interface People extends Name, Age { height: number } Is there a similar way to achieve this with Zod? What I attempted ...

What are some creative ways to design the mat paginator in Angular?

Looking for tips on how to style Angular Material Paginator to match a Figma design? ...

waiting for the import statement in a React/NextJS/Typescript project to resolve

While working on my node.js development server, I encountered a problem with the following code: import { useRouter } from 'next/router' import nextBase64 from 'next-base64'; const Load = () => { const router = useRouter() co ...

Tips for efficiently utilizing mapActions in vue with Typescript class components!

Can someone please provide guidance on the correct way to use ...mapActions([]) within a Typescript vue class component? This is my current approach: <script lang="ts"> import { Component, Prop, Vue } from "vue-property-decorator"; import { mapActi ...

Exploring the Power of SectionList in Typescript

How should SectionList be properly typed? I am encountering an issue where this code works (taken from the official documentation example): <SectionList renderItem={({item, index}) => <Text key={index}>{item}</Text>} renderSectionHea ...

Customizing default attribute prop types of HTML input element in Typescript React

I am currently working on creating a customized "Input" component where I want to extend the default HTML input attributes (props). My goal is to override the default 'size' attribute by utilizing Typescript's Omit within my own interface d ...

Finding the total value of elements within a vector by utilizing intervals

Imagine I have a vector called vect = [1 2 3 4 5 6 7 8 9] and another vector named intervals = [1 3 6 9]. Can I create a new vector consisting of the partial sums of elements in vect, using intervals? I am looking to achieve something like this: Partial s ...