Submitting Selected Rows in Angular Material Table: Implementing a Button Click Event

Although a similar question has been addressed on Stack Overflow regarding how to pass selected row values of a table to a button click event in Material design using Angular 6, I did not find the solutions provided there helpful for my specific case.

In my project, I am utilizing an Angular Material table to display data with a select checkbox next to each row.

The goal I am aiming for is to allow users to select rows of their choice and upon submitting a button, all the selected rows will be sent to the backend for processing. Currently, I have implemented an approach where clicking on the checkbox triggers a function (click)="onSelectCheckbox(row)" in my component.ts, adding the selected row to an array. Deselecting a row invokes the same function and removes the row object using .filter().

While this method functions properly when checkboxes are clicked at a normal speed, it encounters issues when checkboxes are rapidly toggled. Upon submission, the console displays deselected rows still present in the array while selected rows are missing.

The checkbox implementation within my mat-table:

<ng-container matColumnDef="select">
     <th mat-header-cell *matHeaderCellDef>
       <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">
       <mat-checkbox (click)="onSelectCheckbox(row)" (change)="$event ? selection.toggle(row) : null"
         [checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)">
       </mat-checkbox>
     </td>
</ng-container>
.
.
.
<button class="btn btn-primary" (click)="openSubmitConfirmation()">Submit</button>

The logic behind the onSelectCheckbox(row) function in my component.ts, as well as the button to display selected rows in the console for testing:

selectedPayment = new Array<Payment>();

onSelectCheckbox(row: Payment) {
    if (this.selectedPayment === undefined || this.selectedPayment.length === 0) {
      this.selectedPayment.push(row);
    } else if (this.selectedPayment.includes(row)) {
      this.selectedPayment = this.selectedPayment.filter(
        x => x.payment_reference !== row.payment_reference);
    } else {
      this.selectedPayment.push(row);
    }
  }

openSubmitConfirmation() {
    console.log(this.selectedPayment);
  }

I am certain that there must be a more efficient way of achieving this functionality, but I have yet to come across any valuable resources. Any guidance or suggestions would be greatly appreciated.

Answer №1

If you want to retrieve all selected elements at once, consider using SelectionModel

SelectionModel is available in @angular/cdk/collections

You can view a live example I created on StackBlitz by visiting this link

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

Implementing socket.io in a node.js server with express to showcase a welcome message upon user login

Currently, I am in the process of creating a web chat client using socket.io. However, before I can proceed with this project, I need to establish communication between my server and the website on localhost. Despite receiving the 'listening' me ...

The material picker consistently shows the first day of the month from the assigned date

I'm currently using a material datepicker and attempting to assign a value to it from the server. The response I receive is: 21-07-2022 Since the datepicker requires a date or moment type, I am converting the response accordingly this.form.controls[ ...

Tips for developing a sophisticated HTML quiz

I have spent countless hours perfecting this quiz. I have successfully created a quiz that reveals solutions at the end, but I want to take it one step further. I envision the answers appearing after each incorrect response from the user, and no answer sho ...

Triggering the body onunload event

I am currently developing a HTA that needs to make final modifications on the onunload event. However, I am facing an issue as the event does not appear to be triggered. Can someone confirm if this event is still supported? Is there an equivalent event in ...

On a smaller screen size, the event listeners I add dynamically are successfully attached using the exact same HTML, however, they fail to attach on a larger screen size

I recently created a small website where I dynamically add code to HTML divs. Once the data is set, I attach click and mouse enter/leave events using the div's ID. The site consists of plain HTML, javascript, and CSS. However, I noticed that when I v ...

Trouble with closing windows in the in-app browser on Android devices

Is there a method to successfully close the in-app browser? Despite window.close working on iOS devices, it is not effective on Android. I have experimented with alternatives like window.top.close and window.open("", "_self") window.close, but none have ...

Which npm package is most recommended for integrating the Google Maps platform with NEXTJS?

Struggling with integrating Google Maps Platform into my Next.js project. Despite thorough searching, I haven't found a suitable npm package or clear implementation instructions. Any recommendations or guidance on how to effectively integrate Google M ...

Utilizing a npm module in a web browser following importing in Node.js

I recently installed an npm module, but I'm having trouble figuring out how to use it in the browser after importing it. First, I installed the npm module using the following command (using a dummy example module): npm install sample-module In my p ...

The Distinction Between "Q" and "q" in AngularJS and RequireJS

Currently, my project involves developing a single page application using AngularJS, Breeze, and RequireJS. While trying to configure AMD with requirejs to integrate Angular and Breeze, I ran into an issue related to Breeze's dependency on "q". Intere ...

My experiences with Angular Custom Form Controls have shown that they do not cause my form

I have encountered an issue with my custom form control. Despite changes in the value, the form does not get marked as dirty. I am unsure of what steps need to be taken. Below is the code for my custom component: import { ThrowStmt } from '@angul ...

Using RxJS to merge various HTTP requests into a unified and flattened observable array

Struggling with combining multiple http get requests simultaneously and returning them as a unified, observable array. In my current setup, the method returnNewCars() retrieves Observable<ICar[]> by executing a single http get request. However, in t ...

Encountering a 404 error with an Angular 2 application deployed on Amazon S3

After successfully deploying my Angular2 application on Amazon S3, I noticed that all routing functions properly when navigating using routeLinks/code. However, the problem arises when I refresh the page or try to access a particular route directly - a 40 ...

Is NATS.io compatible with React Native?

Struggling with integrating nats.io into a React Native project using Typescript has presented many challenges. Is there a way to successfully incorporate it without having to modify node_modules of nats (such as changing the "fs" import to "react-native-f ...

Ways to extract the text from a modifiable div using angularjs

I am currently facing a challenge in extracting content from an editable div. I am having trouble incorporating the Angular template for this task. The part that is posing a difficulty for me is figuring out how to link model data from the HTML template t ...

Leveraging JSON Data in Highcharts

I am looking to create a column range chart using Highcharts to display a series of high and low temperatures. I found a demo example that showcases the kind of chart I want on the Highcharts website at: http://www.highcharts.com/stock/demo/columnrange Th ...

Strategies for capturing a 404 error in an Express router

Trying to capture the 404 page not found error in an express router. Using a simple example : const express = require('express'); const app = express(); const router = express.Router(); // ROUTER MID BEFORE router.use((req, res, next) => { ...

Node.js implementation to transfer MongoDB to CSV, with the unfortunate loss of certain columns

I have a script that exports a MongoDB table to CSV but I seem to be missing some columns. It appears that the column with many null values (where the first 100 rows are all null) is not being included in the exported CSV file. const mongodb = require(" ...

Angular form directive for managing arrays

export class TestComponent implements OnInit { models: Model[]; ngOnInit() { // numerous Observable pipes and subscriptions, one of which populates the models } add(): void { let newModel = {...}; this.models.push(ne ...

The compatibility issue arises when trying to utilize Axios for API calls in Ionic 6 React with react-query on a real Android device in production. While it works seamlessly on the emulator and browser

My form utilizes react-hook-form to submit data to a server. Here is the code: <FormProvider {...methods}> <form onSubmit={handleSubmit(onIndividualSignup)}> <Swiper onSwiper={(swiper) => setSlidesRef(s ...

Troubleshooting Typescript Compilation Error in React - Cannot assign type 'Element' to type 'FunctionComponent<{}>'

The code snippet originally utilized - import { Create } from '@material-ui/icons'; <DroppableFolder count={draftsCount} sidebarOpen={open} folderId={FolderType.Drafts} Icon={Create} name="Dr ...