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

TypeORM: When generating a migration, a SyntaxError is thrown stating that an import statement cannot be used outside a

While configuring TypeORM in my NextJS TypeScript project, I encountered an issue where I received the error message: SyntaxError: Cannot use import statement outside a module when attempting to create migrations for my entities. ...

Angular4 ASP.NET Core project does not seem to be detecting the API endpoints

I am encountering an issue with my angular application where I consistently receive a "Cannot match any routes" error when attempting to access certain api resources. The base in my application is configured as <base href="/"> and the api source is ...

Generating dynamic forms using JSON Schema in Angular 8 can greatly streamline the form creation process

Struggling with generating dynamic forms from JSON Schema in Angular 8, I stumbled upon a couple of libraries. One seemed outdated with its last commit around 2 years ago, while the other appeared to be a more recent fork of it for Angular 8. The first li ...

Can you provide some guidance on utilizing a for loop within Angular?

Storing the values entered by the user in an input field as "values" and having another array, "existing userdetails," returned from the backend that contains all details of existing users, I am faced with the task of comparing these two sets of data. I h ...

When using translate.get with an array of strings in Angular 5, the function will return both the keys and values, not just

Currently, I am utilizing Angular 5 to manage internationalization through ngx-translate within my code. To elaborate on the issue at hand, I have a data table that pulls information from a web service and displays it correctly. There is also a button tha ...

CSS - Text and dropdown misalignment due to spacing issue

I'm looking to decrease the spacing between the text "Allow type of Compartment Option" and the dropdown box. Here is the code snippet being used: .cl-checkbox { padding-left: 20px; padding-bottom: 10px; padding-top: 20px; ...

Adding an element to an array in Angular 2 when an object is clicked

Whenever a row of objects is clicked, I want it to be added to the selectedProducts array. Within my TypeScript file: selectedProducts: Product[] = []; select(product) { this.selectedProducts.push(product); console.log(this.selectedProducts); ...

Filtering an observable using criteria from another source

I'm currently facing a challenge where I need to map observables by filtering them based on events emitted from other observables. The main question at hand is: Is there a way to pass a property of an event to a filter function? In the following exa ...

Issue with debugging Azure Functions TypeScript using f5 functionality is unresolved

I am encountering issues running my Azure TypeScript function locally in VS code. I am receiving the errors shown in the following image. Can someone please assist me with this? https://i.stack.imgur.com/s3xxG.png ...

Using immer JS to update a nested value has been successfully completed

What is the most efficient way to recursively change a value using a recursive function call in a Produce of Immer? The WhatsappState represents the general reducer type, with Message being the message structure for the application/db. type WhatsappState = ...

Discovering Child Elements in Angular 2 with @ViewChild and CSS Selectors

I'm looking to update the style of the second paragraph using either the nth-child() selector or by a specific class: import { Component, ViewChild } from '@angular/core'; @Component({ selector: 'my-app', template: ` <d ...

Having trouble with setting a default radio button selection in an Angular form within Ionic 4 framework

I am currently working on an application using Ionic to design a form that includes radio buttons. I have been attempting to set one of the radio buttons as checked by default, but so far, nothing seems to be effective. I have tried various methods, such a ...

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 ...

What is the best method to create a TypeScript dictionary from an object using a keyboard?

One approach I frequently use involves treating objects as dictionaries. For example: type Foo = { a: string } type MyDictionary = { [key: string]: Foo } function foo(dict: MyDictionary) { // Requirement 1: The values should be of type Foo[] const va ...

Merge three asynchronous tasks into a single observable stream

I have 3 different observables that I am using to filter the HTML content. Here is the TypeScript code snippet: fiscalYear$ = this.store$.select(this.tableStoreService.getFiscalYear); isLoading$ = this.store$.select(this.tableStoreService.tableSelector ...

Utilizing Mongoose to fetch data from Atlas MongoDB for integration into an Angular application

I recently made some updates to my signup page by adding a new input field for the user's name and adjusting the schema settings accordingly. How can I now retrieve this name to use in both my post-list component and post-create component? Here is an ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

What is the best way to merge two approaches for tallying items within each category?

I have an Angular 8 application that includes two methods for displaying the number of items in each category. These items are retrieved from the back-end and are categorized as follows: <mat-tab> <ng-template mat-tab-label> ...

Troubleshooting problems with Angular 6 update through the command "ng update"

https://i.stack.imgur.com/LuPSs.png I am currently in the process of upgrading from Angular version 5 to 6. When using the "ng update" command, I encountered a problem that is shown in the attached screenshot. Can someone guide me on how to resolve this ...

Optimize Next.js 10 TypeScript Project by Caching MongoDb Connection in API Routes

I am currently in the process of transitioning next.js/examples/with-mongodb/util/mongodb.js to TypeScript so I can efficiently cache and reuse my connections to MongoDB within a TypeScript based next.js project. However, I am encountering a TypeScript err ...