What are some ways to retrieve a summary of an Angular FormArray containing controls?

In my FormGroup, I have a FormArray called products which contains dynamic controls that can be added or removed:

FormGroup {
  controls {
    products (FormArray) {
      0 : {summary.value: 5}...
      1 : {summary.value: 8}..
there can be N of these controls...
    }
  }
}

The expected summary value is 5+8 = 13.

I need to retrieve all the summary values and calculate their sum. How can I achieve this?

This is what I've attempted so far, but it's not working as intended:

   calculateAllSummary(formGroup: FormGroup) {
      Object.values(formGroup.controls.products['controls']).forEach((value: FormControl) => {

                let summaryControl: FormControl = value['controls'].summary;
                this.summarySubscription = summaryControl.valueChanges.subscribe(val => {
                    if(this.checkIfValuesArentTheSame(val) == true){
                        let price = val;
                        if (price != null && typeof price == "string") {


                price = price.split(',').join('');
                    }
                    let numericValue = 0 + Number(price);
                    this.summaryValue = this.dp.transform(numericValue, '2.2-5');

                };
            },
            (error) => {
                console.log(error)
            },
            );
    });
}

The issue with my code is that whenever I input a new summary for another product, it overrides the previous one instead of adding to it. This is due to the line

let numericValue = 0 + Number(price)
, but I'm unsure how to approach this problem differently.

Answer №1

Minimize the properties in your object.

const formData = {
  detailOne: '5',
  detailTwo: '8',
  someFieldToOmit: 'LOL'
};

const totalDetail = Object
  .entries(formData)
  .filter(([key]) => key.toLowerCase().includes('detail'))
  .reduce((acc, [, value]) => acc += +value, 0);
  
console.log(totalDetail);

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

Troubleshooting Angular 2 RC5: detectChanges function not functioning as expected

Currently, I am working on developing a login form component that has the following interface: <login-form onlogin="submit()"></login-form> Here is the testing code for this component: it("Ensuring credentials are passed correctly out of t ...

Guide to deploying Angular application on a weblogic server using a WAR/EAR file

I am facing difficulties deploying an Angular application on a WeblogicApplication server. My current approach is not yielding successful results: This is what I have done: 1) Built my Angular application using exec-maven-plugin and placed the result i ...

What methods are available to restrict the values of properties to specific keys within the current type?

I am looking to declare an interface in typescript that is extensible through an indexer, allowing for the dynamic association of additional functions. However, I also want sub properties within this interface that can refer back to those indexed functio ...

A guide on retrieving the values of all child elements within an HTML element using Puppeteer

I have been exploring the capabilities of puppeteer and am trying to extract the values from the column names of a table. <tbody> <tr class="GridHeader" align="center" style="background-color:Black;"> <td cl ...

Tips for accurately extracting values from a decoded JSON

Hello, I am posting this query because I recently encountered an issue with json encoding in PHP. When using the json_encode() function, my original JSON data gets converted to strings instead of maintaining its original variable type. For instance, let&a ...

What is the process for including an object in an http.post request?

My contact object needs to be included in the http.post method. I'm struggling with where exactly to pass this contact parameter. Can you provide guidance on how to modify my code accordingly and also share any relevant links related to the http.post ...

Unable to assign a default value to an Angular input field

My web page utilizes an Angular form to display user data fetched from a MongoDB database. The information includes the user's name, phone number, email, etc. I want the default value of the input field to be set as the placeholder text, allowing user ...

Looking for a way to notify users about page expiry with an Angular 5 service?

I have multiple pages each containing numerous forms. I am looking to develop a monitoring service for these forms. These forms are connected to data model objects with a high number of properties. I attempted to use the watchjs library to track changes in ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

How can I add a dropdown filter to column values in ag-grid?

I'm attempting to implement a dropdown filter for a column in an ag-grid using Angular 8. I've successfully displayed the column with the following code: columnDefs = [ { headerName: 'Id' , field: 'id' ...

The error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...

Tips on properly declaring props in Typescript when a parent component is passing props down to its children componentsуж

When a parent component clones its children to pass props to them, how can we specify the type of props for the children? I'm encountering an issue because injectedProps is expected in the Child component const Parent: React.SFC<ParentProps> = ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Having trouble with NextJS TypeScript and the randomUUID?() function? If you're seeing the error TS2386 that says "Overload signatures must all be

In my project setup, I have a mono-repo structure utilizing Lerna for managing 2 NextJS projects and 1 shared project. I recently attempted to integrate typescript. The NextJS projects seem to be functioning correctly (following the documentation), but I ...

What is the specific purpose of the 'extend' keyword in Typescript?

Recently, I have been delving into the realm of Javascript/Typescript/React as a PHP developer. During my learning process, I encountered a few perplexing issues that I could not fully grasp. In light of this, I am reaching out to the experienced indiv ...

The zip() operator in RxJS is not functioning as intended. It consistently finishes execution without emitting any values

Suppose you have an observable containing a large number of elements, say 450 or more. You want to transfer these elements to a different observable in batches of 100 elements each. You can check out a functional example provided by @martin at this link: ...

Issue occurred when trying to load controllers during the migration process from AngularJS1 to Angular6

Currently, I am in the process of upgrading AngularJS1 components to Angular6. My strategy involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and storing them under the folder "directive-wrappers". However, wh ...

Problem with TypeScript involving parameter destructuring and null coalescing

When using parameter destructuring with null coalescing in TypeScript, there seems to be an issue with the optional name attribute. I prefer not to modify the original code like this: const name = data?.resource?.name ?? [] just to appease TypeScript. How ...

The .value property on the form group displays numeric values as either null or an empty string

I'm encountering an issue with extracting data from a form group. Within my code, there is a formGroup named lineitemForm, and I am attempting to structure this form group as follows: private formatTransferData() { const depositDates = this.get ...

Opening a new tab in Angular 6 from a component with freshly generated HTML (containing input data)

Hello everyone. I have a requirement where I need to open a new browser tab with formatted input data from a modal component. Here's an example code snippet that attempts to achieve this using ng-template: @Component({ template: '< ...