Unable to clear all checkboxes after deleting

In my application, there are 3 checkboxes along with a master checkbox that allows users to select or deselect all of them at once.

Everything works fine with the master checkbox until I delete some rows from the table. After deleting data, I can check the master checkbox to select all the remaining checkboxes, but then I encounter an issue when trying to deselect them. Here is a visual representation:

https://i.stack.imgur.com/tzd9e.gif

<table mat-table [dataSource]="serviceTable" #matTableService class="mat-elevation-z8">
  <!-- Checkbox Column -->
  <ng-container matColumnDef="select">
    <th style="width: 200px" mat-header-cell *matHeaderCellDef>
      <mat-checkbox [checked]="selection.hasValue() && isAllSelected()" (change)="toggleAllServices()" [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>
    </th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox [checked]="selection.isSelected(row)" (change)="selection.toggle(row)"> </mat-checkbox>
    </td>
  </ng-container>
selection = new SelectionModel<Services>(true, []);

toggleAllServices(): void {
  console.log(this.selection.selected, 'selected')
  console.log(this.serviceTable, 'services');
  if (this.isAllSelected()) {
    this.selection.clear();
    this.allServicesAreSelected = false;
    return;
  }
  this.selection.select(... this.serviceTable);
  this.allServicesAreSelected = true;
}

isAllSelected(): boolean {
  return this.selection.selected.length === this.serviceTable.length
}

When I need to delete rows, I use the following method:

deleteMultipleServices():void {
  const SELECTED_IDS:Array<number> = [];
  for (let item of this.selection.selected) {
    SELECTED_IDS.push(item.id);
  }
  this.serviceTable = this.serviceTable.filter((serviceValue, i) => !SELECTED_IDS.includes(i))
  this.matTableService.renderRows();
}

My problem arises after deleting a row - the if-statement if (this.isAllSelected()) { is never triggered. This is because this.serviceTable correctly returns 2 objects, but this.selection.selected still shows 3 objects even though one has been deleted. How can I solve this discrepancy?

Answer №1

Once you've removed any unwanted items, make sure to reset the selection.

To achieve this, simply use the following code snippet:

this.selection.reset();

Answer №2

Give it a shot:

<ng-container matColumnDef="select">
    <th style="width: 200px" mat-header-cell *matHeaderCellDef>
      <mat-checkbox [checked]="selection.hasValue() && isAllSelected()" (change)="$event ? toggleAllServices() : null" 
      [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>
    </th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox [checked]="selection.isSelected(row)" (change)="$event ? selection.toggle(row): null"> </mat-checkbox>
    </td>
  </ng-container>

Answer №3

Give it a shot, I'm confident this will do the trick

Once you remove the row, make sure to assign an empty array to selection because it currently holds the previous value (meaning the deleted value).

Include this line in the deleteMultipleServices method or wherever you update dataSource after removing the row:

this.selection = new SelectionModel<Element>(true, []);

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

Utilizing the validator in Vue with the setup script, TypeScript, and the composition API

While working on some code from a tutorial, I came across the challenge of implementing a validator in a similar fashion to the example provided. My task involves utilizing the script setup, typescript, and the composition API. props: { image: { ...

What is behind the inconsistency of RxJS versions?

Trying to set up a node/angular2 solution on cloud9 has been quite the challenge. Below is my package.json: { "name": "example", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www", "postinstall": "typings install", ...

What is the process of hosting an Angular application on a pre-existing Node.js server?

I am currently working on an Angular 6 application that communicates with an existing Node.js API application. Up to this point, I have been using the following command to run and build my Angular application: ng serve Now, I am interested in serving m ...

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

Combining HTTPHandler Observable with another in HTTPInterceptor (Angular 8)

In our Angular 8 project, we have set up our API so that the response includes both a "data" attribute and an "errors" attribute. It's possible for there to be data as well as errors in the response, and we need access to both in the calling component ...

Reduce the size of the JSON file located in the Assets folder during an Angular build

What is the most effective method to compress JSON files in an Angular production build? I currently have a JSON file in the assets folder that remains unchanged when the production build is completed. During development, the file appears as the Developme ...

Is there a way for my React application to detect changes in an npm package?

I am currently customizing an npm package for my application, but I am facing issues with it not being detected when starting my development server. Previously, I was able to resolve this by removing the library and reinstalling it, followed by replacing t ...

Navigating session discrepancies: Combining various social media platforms using Next.js and NextAuth

Recently, I ran into a problem where, upon logging in with Google, I found myself needing access tokens for Twitter and LinkedIn to send out API requests. The issue came about when NextAuth modified my session data to be from either Twitter or LinkedIn ins ...

Accessing the constants and state of child components within a parent component in React

I've created a MUI TAB component that looks like this <Box sx={{ width: "100%" }}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

Utilizing the power of HTML5 drag and drop functionality in conjunction with Angular Material 2's md

When working with Angular Material 2 and attempting to enable reordering of list elements, I encountered an issue where the functionality works perfectly for li-tag but fails with md-list-item. Why is that? Here is a snippet of my template: <md-nav-li ...

Using JavaScript, generate an array of objects that contain unique values by incrementing each value by 1

I have an array of objects called arrlist and a parameter uid If the property value has duplicate values (ignoring null) and the id is not the same as the uid, then autoincrement the value until there are no more duplicate values. How can I achieve the a ...

Generating PDF files from HTML using Angular 6

I am trying to export a PDF from an HTML in Angular 6 using the jspdf library. However, I am facing limitations when it comes to styling such as color and background color. Is there any other free library besides jspdf that I can use to achieve this? Feel ...

closing custom components in Ag-Grid React columns

I am currently utilizing version "27.1.0" of "ag-grid-react". In order to display a custom column component that presents a set of options and closes when the user makes a selection, I need it to trigger an API call. Since this component does not re-render ...

Using curly braces in a fat arrow function can cause it to malfunction

Could someone provide insight into why this code snippet functions as intended: filteredArray = contacts.filter( (contact: Contact) => contact.name.toLowerCase().includes(term.toLowerCase()) ); while this variation does not: filteredArray = contact ...

Ways to improve the feedback for Typescript when dealing with the potential existence of a nested method

Recently encountered a critical bug that I believe could have been identified with the right TypeScript setup. Struggling to come up with a suitable title, so please bear with me. While initializing a widget app, similar to a chat app loaded by a parent a ...

Svelte warns of potential undefined Variable when using "bind:this={}"

Whenever I attempt to utilize the bind:this attribute in Svelte, I encounter this message in vscode: 'cardGroup' is possibly 'undefined'.js(18048) Upon execution, the following error arises: TypeError: Cannot read properties of undefin ...

What is the best way to display individual records from a Web API on the user interface?

Just a heads up: I'm unable to utilize pagination (skip, take) due to the data being sourced from multiple tables. For more information, you can refer to the Report model. I attempted to retrieve the data individually on the UI through WebAPI. The ...

Guide to releasing your Angular 6 library to npmjs along with a detailed README.md

I'm currently in the process of developing an Angular 6 library that I intend to share on npmjs. The library, named ng-as-multiselect-dropdown, is versioned on GitHub through the workspace project 'sample'. I used the Angular-CLI command &ap ...

How can variables within nested ngFor loops be referenced in Angular 1.5 compared to Angular 10?

This particular piece of code was functional in Angular 1.5. It featured a condition where the <tr> element would only be displayed if the 'showFields' flag for that specific row key was set to true. <table> <ng-container *ngIf=& ...