An effective method for displaying the total sum of selected row data in Angular dynamically

My goal is to dynamically show the sum of selected column data using the SelectionModel on the rows that I have selected in my table. The displayed data should update when I select or deselect rows.

I initially believed that utilizing ngOnInit() would help me achieve this, but unfortunately, the total sum of selected column data remains unchanged.


totalWeight = 0;

ngOnInit(): void{
this.selection.selected.forEach((element) => {
this.totalWeight += element.weight;
});
}

You can view a demonstration of this issue on Stackblitz here.

Answer №1

To determine the cumulative sum whenever the checkbox value changes, it is essential to calculate the total.

 updateTotal(row?: PeriodicElement)
  {
    this.totalWeight = 0;
    this.selection.selected.forEach((element) => {
      this.totalWeight += element.weight;
    });
  }

Check out the STACKBLITZ DEMO here.

Answer №2

It is recommended to utilize the changed event within the SelectionModel API, which triggers a SelectionChange event when the selection undergoes changes, instead of relying on the selected variable from the same API.

The SelectionChange interface consists of the following properties (extracted from the source code):

/**
 * Event triggered when the value of a MatSelectionModel has been altered.
 * @docs-private
 */
export interface SelectionChange<T> {
  /** The model that initiated the event. */
  source: SelectionModel<T>;
  /** Items that were added to the model. */
  added: T[];
  /** Items that were removed from the model. */
  removed: T[];
}

Subsequently, you can adjust the weight in the totalWeight property by either adding or removing it using the following method:

totalWeight = 0;

ngOnInit(): void{
  this.selection.changed.subscribe(change => {
      console.log('Added items:', change.added);
      console.log('Removed items:', change.removed);
      console.log('Source selection model:', change.source);
      change.added.forEach(element => {
          this.totalWeight += element.weight;
      })
      change.removed.forEach(element => {
          this.totalWeight -= element.weight;
      })
  });
}

View updated demonstration

Answer №3

Despite the question being resolved and the issue explained, let me demonstrate how you can approach it reactively:

TS:

const totalWeights$ = this.selectedItems.changed.pipe(
  map(() => this.selectedItems.items.reduce((acc, val) => acc + val.weight, 0)),
  startWith(0)
);

HTML:

<p>Total combined weight of selected items: {{ totalWeights$ | async }}</p>

DEMO

Answer №4

To start off, you need to create a function that will calculate the total weight of each change event:

<mat-checkbox (click)="$event.stopPropagation()"
                (change)="$event ? selection.toggle(row) : null;calculateWeight(row)"
                [checked]="selection.isSelected(row)"
                [aria-label]="checkboxLabel(row)">

Next, in your typescript file, using the reduce method, you can achieve this:

public calculateWeight(row?: PeriodicElement){
  this.totalWeight = 0;
  this.totalWeight = this.selection.selected.reduce((prev, cur)=>{
   return prev + cur.weight;
  }, 0);
}

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

Choose the initial full text that corresponds with a portion of the text

I am currently working on a page with multiple <string> tags containing different strings, like 'Is this a String?  Yes'. My goal is to use JQuery to locate the first instance of 'Is this a String?  ' and extract either ...

What are the drawbacks of utilizing the onClick function in JavaScript?

What is the rationale behind programmers opting not to use onClick function in Javascript? ...

What is the best way to transfer the search query to a table filter when working with multiple JavaScript files?

I am struggling with passing the search query from my search file to my table file. The data for my datagrid table is retrieved from a database using an API call, and the table code is in one file while the search functionality code is in another file. I h ...

Disable the functionality of the device's back button to prevent it from going back to the

For my project, I utilize popups to display important information to the user. When a popup is displayed, how can I override the functionality of the device's back button so that instead of navigating to the previous route, it will close the popup? ...

What is causing the issue with mongoose populate not working when trying to populate an array?

My database setup includes 2 schemas: const mongoose = require('mongoose'); const PinSchema = new mongoose.Schema({ title: String, content: String, image: String, latitude: Number, longitude: Number, author: { type: mongoose.Sch ...

What is the best way to make mouse and touch events trigger responses in Angular versions 9 and above?

I've been searching high and low for a library or tried-and-true method to handle common user events reactively, but unfortunately my quest has come up empty. After some digging, I stumbled upon what seemed like a solid solution: https://github.com/t ...

The Angular.js UIBootstarp Timepicker is displaying the "ng-invalid" class when used with an input type of "number"

Currently, I am working on incorporating a time picker using UIBootstrap and angular.js. By default, the timepicker utilizes {{input type="text}} for capturing hours and minutes. However, since I intend to use this feature on mobile devices, I need to di ...

Comparing unique values between objects in JavaScript with varying keys

I'm facing a peculiar issue that I can't seem to solve. I have two variables named nft and web3.givenProvider. Both of them have an address value of "0x0000000000000", but they are stored under different keys - nft is under .seller and ...

What is the role of the "prepare" function in AWS CDK constructs?

TL;DR: What is the role and purpose of the prepare(): void method in AWS CDK's Construct class? When and how should it be utilized or avoided? The information provided about prepare() states: prepare() function is called after child constructs have ...

Autoheight iframes, similar to those found on eBay,

Is there a method to adjust the height of an iframe in the y-axis so that the content properly fits within it? The challenge lies in finding solutions that work within the constraints imposed by modern CORS and Same Origin policies enforced by web browser ...

hide bootstrap confirmation when clicking off of it

I'm facing an issue with the bootstrap confirmation plugin. I want to close all confirmations when the user clicks outside of the confirmation pop-up. However, the current implementation is causing the confirmation to close everytime there is a click ...

Utilizing JSON instead of GeoJSON with AJAX in Leaflet

I am in search of a method to utilize JSON instead of GeoJSON with leaflet, making use of AJAX. The use of JSON and AJAX is imperative for this task. I have successfully called a JSON file using AJAX. However, I am now unsure about how to effectively util ...

Retrieve the URL of a particular XML document from the server using a PHP script, then dynamically load it into a JavaScript file for further processing

As I work on my website, users have the ability to upload and download files while I generate an XML log with operation details. One page on the site displays a table created by reading this XML log. Everything functioned properly when it was all stored l ...

Error: The token < was not expected in ng2 bootstrap code

Having encountered the error Unexpected token < while using ng2 bootstrap, I included 'ng2-bootstrap': 'node_modules/ng2-bootstrap' in the configuration file below. System.config.ts (function (global) { System.config({ ...

Is it possible to execute in a specific context using npm?

I am seeking to execute npm scripts that are executable by VuePress. For instance, I have VuePress installed and would like to run the command vuepress eject. Although I can access vuepress in my scripts, there is no specific script for eject: "scr ...

Transfer the scroll top value from a textarea to a div element

In the parent div, there is a div and a textarea. I am attempting to synchronize the scrollTop value of the textarea with the div so that they move together when scrolling. The issue arises when I input text into the textarea and hit enter for a new line. ...

What is the best way to design a drop-down suggestion list similar to Google's?

This question is still in the theoretical stage, but it's something I'm definitely considering for the long run. When you visit google.com and type in a search query, the site provides suggestions in a dropdown menu. I'm pretty sure they use ...

Tips for chaining API calls in Angular using rxjs?

How can I efficiently nest API calls in Angular using RxJS? getProducts(): Observable<any> { return this.getProductIDs().pipe( map((response) => response.products.map((data) => (item: any) => flatMap(() => th ...

Minimize the amount of external asynchronous calls made by the client

In my application, the client initiates multiple asynchronous JavaScript requests to third party servers. The issue I'm encountering is that when the client responds to these requests, the site becomes inactive for a brief period of time. This inactiv ...

Trouble encountered when trying to populate a dropdown column with dynamic data using ajax

In an attempt to populate and append a column, such as Id, with dynamic data using jQuery and AJAX. The data is supposed to be fetched via a rest webservice but seems to be not populating correctly. Below is the code snippet: This pasted code may not wo ...