calculate the combined values of the array using a reactive form

I am currently dealing with a reactive form that consists of a formArray containing multiple formGroups.

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

Each formGroup corresponds to an array of objects based on the selection made in the age field. For example:

For formGroupName[0], the resulting array is:

[
  0: {aseguradora: "name1", plan: "plan1", prima: 6670}
  1: {aseguradora: "name2", plan: "plan2", prima: 3272}
]

For formGroupName1, the array looks like this:

[
  0: {aseguradora: "name1", plan: "plan1", prima: 9302}
  1: {aseguradora: "name2", plan: "plan2", prima: 4616}
]

This pattern continues for other formGroups as well.

Now, my goal is to create a new Array that sums up the prima values from all groups. If a formGroup is removed, the sum should be adjusted accordingly.

In essence, I want the final result to be:

[
  0: {aseguradora: "name1", plan: "plan1", prima: 15972}
  1: {aseguradora: "name2", plan: "plan2", prima: 7888}
]

I have attempted the following approach, which calculates the sum but doesn't adjust it when a formGroup is deleted:

  control.at(+i).get('edad').valueChanges.subscribe( res => {

    // Fetching the Array
    this.primasFilter = this.primasSalud.filter(fil => fil.edad === res);
    this.primasFilterEdad = this.primasFilter[0].primas;
    console.log(this.primasFilterEdad);

    // Calculating the sum
    this.saludPreferencial = (this.primasFilterEdad[0].prima);
    this.totalSumSaludP += this.saludPreferencial;
    console.log(this.totalSumSaludP);

  });

Answer №1

Avoid using a "counter" and instead calculate the total sum each time by iterating through all the values. For example:

this.totalSumSalidP = this.array.value.map(x => x.prima).reduce((a, b) => (+a) + (+b), 0)

This method should be effective.

IMPORTANT: Remember that in the code, "this.array" is a getter function.

get array(){
   return this.myForm.get(...) as FormArray
}

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

What are the steps for designing personalized syncfusion grid-columns while still preserving the built-in search functionality of syncfusion?

Looking to transform the data coming from the backend, specifically mapping a user's status which is represented as a number to its corresponding string value. Considered using typescript for this mapping task, but it interferes with syncfusion' ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

When the admin clicks the start button, redirect all users to the designated page

Currently, I am developing a voting application that features both an admin and users. My goal is for the voting campaign to kick off as soon as the admin clicks on the start button. Upon starting the voting process, I aim to redirect all users to a diff ...

Guide on declaring package.json during library publication in Angular 6

Building node modules using Angular6 should be a breeze. The Documentation outlines the following steps: ng generate library YOUR-LIBRARY ng build YOUR-LIBRARY --prod cd dist/YOUR-LIBRARY && npm publish By following these steps, a new project wi ...

Enforcing alias types in TypeScript arguments is necessary for maintaining consistency and clarity

I'm currently facing a challenge with type unions and aliases. I have an alias for values that can possibly be null or undefined, along with a function that handles these values. Everything is running smoothly and safely. However, there are instances ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

Is there a way to trigger the click event in the week view of an Angular 2+ calendar?

https://i.sstatic.net/Vx2x8.png HTML Templates <mwl-calendar-week-view [viewDate]="viewDate" [refresh]="refresh" (click)="weekDayClick($event)"> </mwl-calendar-week-view> In the component file weekDayCl ...

Error message in Docker: "Command /bin/sh: 1: ng: not found; please make sure Angular

While attempting to create a docker image for my Angular app, I encountered an issue where it crashes on RUN ng build --prod and the error message displayed is: /bin/sh: 1: ng: not found The command '/bin/sh -c ng build --prod' returned a non-ze ...

Adjusting SVG Viewbox dynamically in Angular 7 through manipulating path dimensions

I am working with a library of SVG icons in JSON format. Each icon has an associated key for its name and a path used to render it, and they come in various dimensions. I have created an icon component that takes the JSON data and generates an SVG by using ...

Sending information to a deeply nested child component in Angular 4

Here is the structure of components in my Angular application: app.component.html units.component.html section.component.html {{appData.title}} I have created "appData" in the app.component.ts and now I want to access it in the third level child co ...

Managing properties of classes within callbacks using TypeScript

I am currently working on the following task: class User { name: string; userService: UserService; //service responsible for fetching data from server successCallback(response: any) { this.name = string; } setUser() { ...

Error: The method "next" cannot be used with BehaviorSubject

My goal is to share data between sibling components by utilizing a shared service. The first component loads and retrieves a list of Servers from the API, populating a select box with all the servers. I now need to notify the other component when the user ...

Ensuring Angular applications can effectively run on Internet Explorer

In my Angular application, I have implemented the functionality where users can choose a map to select the delivery point for goods. However, there seems to be an issue with this feature in Internet Explorer (IE) - the map opens but the delivery points ar ...

Expandable CSS Sticky Header that Grows and Pushes Content Down

I am currently working on implementing a Sticky Header feature, where the header will expand (depicted by the Green Box) if the user selects more documents in the left grid (not shown). I need help figuring out how to achieve this, as most resources recom ...

Parsing a Json object that contains a field with two distinct types, one of which is recursive

In my project, I have a TypeScript component that retrieves JSON data, and I need to parse this JSON in C# to work with the objects. However, due to the presence of: multiple type fields recursion it's becoming challenging to understand how the dese ...

Angular 2: Export Data to CSV and Download

My backend is built in a Spring Boot application where I am returning a .csv file. @RequestMapping(value = "/downloadCSV") public void downloadCSV(HttpServletResponse response) throws IOException { String csvFileName = "books.csv"; ...

Setting input limits in AlertBox in Ionic v3: A step-by-step guide

I am currently working on creating an alert box that includes some inputs. I am trying to restrict the input to a maximum of 10 characters and ensure that only numbers are allowed. Unfortunately, I haven't been able to find any helpful guides on this ...

Leveraging a sophisticated .d.ts file known as chrome-app.d.ts

Understanding and using .d.ts files can be straightforward for most, like jQuery.d.ts. However, I recently encountered chrome-app.d.ts and found it a bit puzzling on how to import this typings file. In chrome-app.d.ts, there are various module definitions ...