The function responsible for displaying totals in the footer is producing inaccurate figures. What steps can be taken to address this

I am working with an Angular Material table that looks like this:

 <table mat-table [dataSource]="mixDetails" matSort matSortActive="index" matSortDirection="asc">
                  <ng-container matColumnDef="select">
                    <th mat-header-cell *matHeaderCellDef style="width: 4%">
                      <mat-checkbox (change)="$event ? masterToggle() : null"
                                    [checked]="selection.hasValue() && isAllSelected()"
                                    [indeterminate]="selection.hasValue() && !isAllSelected()"
                                    [aria-label]="checkboxLabel()">
                      </mat-checkbox>
                    </th>
                    <td mat-cell *matCellDef="let row" style="width: 4%;">
                      <mat-checkbox (click)="$event.stopPropagation()"
                                    (change)="$event ? selection.toggle(row) : null"
                                    [checked]="selection.isSelected(row)"
                                    [aria-label]="checkboxLabel(row)">
                      </mat-checkbox>
                    </td>
                    <td mat-footer-cell *matFooterCellDef style="width: 4%; padding-left: 5px">
                      Total
                    </td>
                  </ng-container>

                  <ng-container matColumnDef="index">
                    <th mat-header-cell *matHeaderCellDef mat-sort-header style="width: 4%">#</th>
                    <td mat-cell *matCellDef="let row; let i=index" style="width: 4%">{{i + 1}}</td>
                    <td mat-footer-cell *matFooterCellDef style="width: 4%">
                      {{mixDetails.data.length}}
                    </td>
                  </ng-container>

                  <ng-container matColumnDef="component">
                    <th mat-header-cell *matHeaderCellDef mat-sort-header>Component</th>
                    <td mat-cell *matCellDef="let row">
                      <div fxLayout="row" fxLayoutAlign="space-between" style="padding-left: 5px" *ngIf="!editMode">
                        {{row.synonym?.compound.compoundName}}
                        <mat-icon *ngIf="row.synonym?.compound.isToxic" style="color: orangered">warning</mat-icon>
                      </div>
                      <div *ngIf="editMode">
                        <ng-select [items]="synonyms"
                                   appearance="outline"
                                   bindLabel="otherName"
                                   bindValue="synonymId"
                                   [clearable]="false"
                                   [(ngModel)]="row.synonymId"
                                   [ngModelOptions]="{standalone: true}"></ng-select>
                      </div>
                    </td>
                    <td mat-footer-cell *matFooterCellDef></td>
                  </ng-container>

                  ...
                           More code here
                  ...

                </table>

In my TypeScript file, I have the getProductTotal function defined as follows:

getProductTotal() {
  var total = 0;
  for (var i = 0; i < this.mixDetails.data.length; i++) {
    total = total + this.mixDetails.data[i].productCharge;
  }

  return total;
}

Everything works fine when the data loads initially, and all numbers and totals display correct values. However, when I enter edit mode and make changes in the product charge column, the total value becomes inaccurate. For example, if the initial values were 60, 20, 25, 50, the total should be 155. After editing, perhaps changing 20 to 45, the total should become 175, but instead, I get incorrect values like 60, 452550. I'm unsure of what I might be doing wrong. If there are any suggestions or guidance on how to resolve this issue, I would greatly appreciate it. Thank you for your assistance.

Answer №1

If anyone else encounters this issue, the root cause was found to be the function overriding the data type of the total and converting it into a string. As a result, instead of adding numbers together, it was concatenating strings. To resolve this issue, I added a plus sign to explicitly convert the string to a number within the function:

total = total + (+this.mixDetails.data[i].productCharge);

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

Is it possible to create a custom range slider using Angular Material 2?

Can Angular Material 2 be used to create a custom range slider? For example, I want to display organization sizes with specific ranges like: 1-10 employees 11-50 employees 51-200 employees 201-500 employees 501-1,000 employees 1,001-5,000 employees 5,001 ...

Declaring scoped runtime interfaces with Typescript

I need to create a global interface that can be accessed at runtime under a specific name. /** Here is my code that will be injected */ // import Vue from "vue"; <- having two vue instances may cause issues // ts-ignore <- Vue is only ava ...

What is the reasoning behind being able to only access a component variable from outside of the component?

I've created a modified version of an example app from an Angular book. To check out the working example (in development mode), visit: You can also find the source code on GitHub here. One of the components, log, contains the variable autoRefres ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

Error encountered in Ionic Angular: Camera-Injection-Error provider is missing in Module.ts

Having some trouble while trying to develop an app with ionic-angular using the Ionic/ngx camera. I keep encountering this error even after adding the camera provider in the module.ts section. View the error here Below is my module.ts file content: impo ...

Seamless Navigation with Bootstrap Navbar and SmoothScroll

Currently, I have a custom-built navbar that functions perfectly, with full mobile responsiveness. However, I am facing an issue with the nav-item's (headings). The nav-item's direct users to different sections of the same page using #. I have i ...

Can you explain the type of the Fat Arrow function or Callback?

Here's a simple question. Coming from a Qt/C++ background, I value explicitness as good practice: protected sanityCheck() : void { ... } // Clear and Type-Safe protected sanityCheck() { ... } // Risky and Insecure Now, how can I achieve the s ...

Tips for avoiding the transmission of className and style attributes to React components

Hey there! I'm working on a custom button component that needs to accept all ButtonHTMLAttributes except for className and style to avoid any conflicts with styling. I'm using TypeScript with React, but I've run into some issues trying to ac ...

What is the best way to divide two ranges that are intersecting?

Seeking a method to divide two overlapping ranges when they intersect. This is my current progress using typescript, type Range = { start: number; end: number; }; function splitOverlap(a: Range, b: Range): Range[][] { let result = []; const inters ...

Creating a TypeScript interface where the type of one property is based on the type of another property

One of my Interfaces has the following structure: export enum SortValueType { String = 'string', Number = 'number', Date = 'date', } export interface SortConfig { key: string; direction: SortDirection; type: Sort ...

Enhance user experience with Bootstrap by automatically adding a frame around a card upon clicking

Hello everyone! I am a beginner in the Angular/Web Development world and I am currently working on improving my HTML/CSS skills. While using Bootstrap in my Angular project, I ran into a challenge that I couldn't figure out on my own. I have implement ...

``There seems to be an issue with the Angular Material Table dataSource, as it is not binding correctly or updating

When examining the served page: <table _ngcontent-c6="" class="mat-elevation-z8 mat-table" fxfill="" mat-table="" matsort="" role="grid" ng-reflect-data-source="[object Object]"> In View: table matSort fxfill mat-table [dataSource]="dataSou ...

Breaking down the steps to flip between two images when clicked in Vue.js

I'm currently trying to implement a feature in Vue.js where images switch on click. The functionality I'm aiming for is as follows: Upon initial load, the image displays in black, then upon clicking/selecting it, the image transitions into a blu ...

Having trouble with reloading the FirebaseAuth widget in an Angular 8 single page application?

I recently developed an Angular 8 CLI project that integrates with FirebaseUI Auth for email and password login. However, I am facing an issue where the FirebaseUI Auth widget does not appear after the user logs out. Is this a bug in the system or am I ove ...

React, Storybook - Error TS2307: Button module not found or its type declarations. Can Storybook resolve this issue?

In my React project, I have a Button component created with "create-react-app" that uses absolute paths for importing. When trying to import { Button, ButtonProps } from 'Button', I encountered an error with TS2307. The absolute path 'Butto ...

Having trouble scrolling in Modal Controller with Ionic 6

When I click on a button, an Ionic modal controller is displayed. However, I am facing an issue where the modal does not scroll when the ion-item within the modal component contains details from an object array. As a result, I cannot see the remaining list ...

Implementing child components in React using TypeScript and passing them as props

Is it possible to append content to a parent component in React by passing it through props? For example: function MyComponent(props: IMyProps) { return ( {<props.parent>}{myStuff}{</props.parent>} } Would it be feasible to use the new compone ...

Exploring various projects within one Angular application

I have a main application with a single child application. I am trying to display the child application when clicking on an anchor link within the main application, but it doesn't seem to be working. Project Structure: one-app -project --scrapper -- ...

Is there a sophisticated method for breaking down a nested property or member from TypeScript imports?

Just curious if it's possible, not a big deal otherwise. import * as yargs from 'yargs'; // default import I'm looking to extract the port or argv property. This would simplify the code from: bootstrap(yargs.argv.port || 3000) to: ...

Angular 5, Karma, Jasmine-jQuery testing toolkit synergizes for precision

How can I incorporate karma jasmine jquery matches with angular 5? Please provide a detailed answer. I have managed to successfully load jQuery in the karma configuration like this: module.exports = function (config) { config.set({ basePath: &apos ...