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

Monitor the status of your Angular CLI build with real-time notifications

Encountered an interesting issue while trying to integrate the 'webpack-notifier' plugin into a new Angular 7 application. The goal was to have balloon notifications for build failures when running 'ng build --watch' in the console. TL ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

Establishing a server in Node.js alongside an Angular 2 frontend by harnessing the power of Typescript

I'm looking to deploy my web application on IBM Bluemix with Angular 2 using Typescript for the frontend and Node.js for the backend. Can you advise me on how to configure the server, connect it to the frontend, and specify which transpiler I should u ...

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

What is the best way to update my data from the parent component?

Hello, I am trying to update the timestamp value from the parent component. This is my ParentComponent.ts file: public updateTimestamp(){ this.timestamp = new Date(); this.timestamp.setDate(this.timestamp.getDate() - 30); this.timestamp = thi ...

Exploring an array in React using typescript

I have a persistent data structure that I'm serving from the API route of my Next.js project. It consists of an array of objects with the following properties: export interface Case { id: string; title: string; participants: string[]; courtDat ...

How to access the state of an @ngrx/data entity in a reducer function in ngrx 8

I am trying to access the state of a ngrx/data entity within a reducer function. Currently, I am working on implementing a pager (pagination) feature where users can navigate through different pages. However, I am facing a challenge in determining the tot ...

Transforming a material-ui component from a class to a function

Currently, I am in the process of learning material-ui, and it seems that most of the code examples I come across are based on classes. However, the new trend is moving towards using functions instead of classes due to the introduction of hooks. I have be ...

All components load successfully except for the worker in Webpack

I've been working on configuring webpack to bundle my react project. I successfully set up the webpack_public_path variable and all modules are loading correctly, except for the worker. const path = require('path'); const MonacoWebpackPlugi ...

Changing data before resolving in Angular Observable

Despite my attempt to transform the data before resolving it, the subscriber is still receiving the non-transformed data. @Injectable() export class OrderService { getAll(): Observable< Array<Order> > { let url = 'http://fakea ...

Issue: "Exported functions in a 'use server' file must be async"

I'm currently working on implementing layout.tsx in the app directory of Next.js 13 to create a navigation layout that appears on all pages. I've successfully configured it so that the navbar updates when a user logs out or signs in, but there&ap ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Promise disregards the window being open

I'm facing an issue with redirecting users to Twitter using window.open in a specific function. It seems like the instruction is being ignored, even though it works perfectly on other pages. Any ideas on how to fix this? answerQuestion() { if ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

Exploring Several Images and Videos in Angular

I'm experiencing a challenge with displaying multiple images and videos in my Angular application. To differentiate between the two types of files, I use the "format" variable. Check out Stackblitz export class AppComponent { urls; format; on ...

The Angular build process was successful on a local machine, however, the Angular build failed when

I am facing a challenge with my Angular project that I want to deploy on Gitlab Pages. Initially, when I execute: ng build --prod locally, the build is successful. Below is my .gitlab-ci.yaml: image: node:8.12.0 pages: cache: paths: - node_mo ...

How can I create an interceptor in Angular2 to detect 500 and 404 errors in my app.ts file?

Creating an Angular2 Interceptor for Handling 500 and 404 Errors in app.ts In my app.ts file, I am looking to implement an interceptor that can detect a 500 or 404 error so that I can appropriately redirect to my HTML 404 or HTML 500 pages. Is this funct ...

The module 'ngx-webstorage/ngx-webstorage' does not have a 'Ng2Webstorage' member available for export

I'm facing an error in my Angular project listed below: ERROR in I:/Apps/App/node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/jit-polyfills.js Module not found: Error: Can't resolve 'core-js/es7/reflect' in ' ...

The received data object appears to be currently undefined

I am currently using MapBox to display multiple coordinates on a map, but I am encountering an issue where the longitude and latitude values in my return object are showing up as undefined. Could there be a missing configuration that is preventing the data ...

Using ngIf for various types of keys within a JavaScript array

concerts: [ { key: "field_concerts_time", lbl: "Date" }, { key: ["field_concert_fromtime", "field_concert_totime"], lbl: "Time", concat: "to" }, { key: "field_concerts_agereq", lbl: "Age R ...