How to calculate the total of a field in an Angular 4 model

How can I calculate the sum of fields N1 to N5 in the Trans model?

public class Trans
{
    public int id { get; set; }
    public int N1 { get; set; }
    public int N2 { get; set; }
    public int N3 { get; set; }
    public int N4 { get; set; }
    public int N5 { get; set; }
}

...

trans: Trans = new Trans();
trans.N1 = 1;
trans.N2 = 2;
trans.N3 = 3;
trans.N4 = 4;
trans.N5 = 5;

...

Then, we want to calculate trans.N1 + trans.N2 + ... + trans.N5

Is there a way to do this?

Answer №1

One way to achieve this is by:

let total = Object.keys(transactions).reduce((total, key) => total + transactions[key], 0);

If you want to exclude the 'id' field, you can add a condition like if(key !== 'id').

To make sure every Transaction object includes this functionality, you can simply add it inside the class (Note: This code should work, but I have not tested it yet):

get totalAmount(): number {
  return Object.keys(this).reduce((total, key) => total + this[key], 0);
}

Answer №2

Create a helper function within your class that calculates the total sum of all elements

public class Trans
{
    public int id { get; set; }
    public int N1 { get; set; }
    public int N2 { get; set; }
    public int N3 { get; set; }
    public int N4 { get; set; }
    public int N5 { get; set; }

    public int sumAllMembers(){
      return this.N1 + this.N2 + this.N3 + this.N4 + this.N5;
    }
}

You can then easily use it by calling trans.sumAllMembers() to get the sum.

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

My attempt to compile my Angular 6 project is encountering an error. The error message points to a problem in the core.d.ts file located within the node_modules folder, specifically on line

Struggling to build my project, I keep encountering the error message shown in the screenshot below. Included is my package.json file with all the dependencies currently being used. I've been stuck with this issue for a few days now and none of the s ...

Angular 2 now has the ability to detect keydown events triggered from any part of the page

Is there a way to enable keyboard control for a view? I attempted using document.keydown, but it wasn't successful. How can I make the document accept keyboard input? A solution that worked for me was implementing this in my component class: @HostLi ...

Form remains unchanged after manipulation in callback

Currently, I have a form with a list of editable objects (constants). Previously, it was possible to delete any object without confirmation. Now, I want to add a ngBootbox confirm step before the deletion process. In my .ts file, the code for deleting an ...

No routes found that match. URL Segment 'calendar' does not correspond to any routes available

Currently interning, I've been tasked with building my own Angular 5 web application. However, I've hit a roadblock with an issue that's had me stuck for hours now. Every time I try to access the calendar, it gives me an error saying it can& ...

Try implementing the Angular 9 Slice Pipe within your ngFor loop

Struggling to figure out how to properly utilize the Slice pipe from Angular within a for loop. Consider this code snippet: textArray = ['aaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbb', 'cccccccccccccccccccc']; <n ...

Changing elements transferred from component to service

Currently, I am in the process of refactoring my code by consolidating common component methods into a shared service. However, I have encountered an issue where I am unable to overwrite a component's public object property that is passed to the servi ...

Is there a way to simulate the @Attribute decorator string provider in an ng2 unit test?

Struggling with unit testing a component and facing a hurdle. Unsure how to mock the functionality of the @Attribute decorator in my test. Error: No provider for String! @Component({...}) export class MyComponent { constructor(@Attribute("handle") pr ...

Developing a dynamic object in Typescript to structure and optimize API responses

Currently Working Explanation: This is similar to the data array received from the API response responseBarDataStacked = [ { sku: "Data 1", month: "Jun", value: 20 }, { sku: "Data 2", month: "Jun", value: 25 ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Identify the Type of a Field in a Typescript Union

I am facing an issue with a union type in my code: type Option1 = { items: string[]; } type Option2 = { delete: true; } type Combined = Option1 | Option2; My goal is to create a new variable that has the same type as the items field: const items_v ...

The functionality to deactivate a button for Angular4 validation is not operating as expected

I am encountering an issue with the submit button in my form. I am attempting to disable it until all the text-boxes are filled. However, it is not working correctly after the page is refreshed or loaded for the first time in the browser. Oddly, if I perfo ...

The autocomplete suggestions appear as faded gray text following the cursor in the input field, rather than displaying as a pop-up selection

My website is built using Angular 10 and Angular Material. I am looking to enhance the input suggestions in matInput, but in a unique way that differs from matAutocomplete. Instead of displaying a list of options, I want to show just one suggestion for a ...

The Express server is set up with CORS enabled, however, it continues to encounter issues when attempting to make asynchronous HTTP requests from

We're currently experiencing an unusual issue and are seeking assistance to resolve it. Initially, our Express server is functioning well as an API when accessed from the same domain. However, we also need to utilize this API on our computers for tes ...

Error: Attempting to access 'update' property of a null value

function logUserOut(user: UserInstance) { return user.update({ token: null }); } I encountered an error at this part of the code. Any suggestions on how to fix it? ...

Increase the number of columns in ion-grid to a maximum of 24 columns by customizing the ion-grid columns

Can anyone assist me in achieving an ion-grid with 24 columns? I was researching the Ionic page (https://ionicframework.com/docs/layout/grid) and came across the property "--ion-grid-columns" under the "Number of columns" section. Unfortunately, there was ...

Steps for setting up Protractor Cucumber Report with TypeScript and screenshots:

I've searched for many tutorials on setting up Protractor with Cucumber reports and screenshots in TypeScript, but have had no luck. Can you provide assistance in configuring this? ...

angular8StylePreprocessorSettings

I'm currently trying to implement the approach found on this tutorial in order to import scss files through stylePreprocessorOptions in Angular 8. However, I'm encountering an error stating that the file cannot be found. Any suggestions on how to ...

Replacing a push operation in JavaScript with a splice operation

Upon entering a screen, 5 promises are automatically loaded using promise.all. The issue is that they are executed in a random order, and within each function, I use a push to store the information. The problem arises when I need to change the push to a s ...

Completion of operator not invoked when encased

Currently, I am utilizing an Angular service to encapsulate some of my http requests for better management of the loading state within my application. This particular service is responsible for keeping track of the status of these calls for future process ...

Tips for narrowing the spacing between bars in a bar graph

Is there a way to decrease the space between bars without increasing the width in an example? I only want to reduce the space but keep the width the same. How can this be achieved? https://i.sstatic.net/cRqaQ.png options: { responsive: false, ...