What is the best method to update the selected checkbox on a mat-table page?

While working on a table project using Angular Material, I encountered an issue with row selections when implementing server side pagination. The logic worked well with local data, but once I switched to server side pagination, the checkboxes' selections didn't render properly when navigating back and forth between pages where rows were previously selected.

private setupCheckboxIfPageChange() {
  console.log(1);
  const selected: TestTable[] = this.selection.selected;
  this.selection.clear();
  this.selection.select(...selected);
}

To address this problem, I created a function that is triggered in the API subscription. You can check out an example of my attempted solution here.

Answer №1

The reason it isn't functioning is because the SelectionModel relies on strict equality (===) as its default, and you're storing objects in the model. If you have two distinct objects returned from different API calls, even if all their properties are identical, they will never be deemed equal. To resolve this issue, consider only storing the IDs of the selected items in the selection model. This adjustment can enhance the efficiency of your application by reducing the amount of data stored in memory.

Updated Stackblitz: https://stackblitz.com/edit/stackblitz-starters-gxci92

If you require the selection model to encompass the entire object, please refer to the alternative solution provided in another answer.

Answer №2

An ideal place to add this code would be inside the ngOnInit() function.

this.selection.compareWith = (a: TestTable, b: TestTable) => a.id === b.id;

If the objects being compared are different, the result will be false.

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

What is the reason for the addEventListener function not being able to access global variables?

I have set up an event listener function to utilize popcorn.js for displaying subtitles. Additionally, I have created functions that are unrelated to popcorn.js outside of the event listener and declared a global variable array. However, when attempting ...

The Three JS library seems to be malfunctioning as it is only displaying a blank, black screen with no

After browsing through similar questions on various sites, I have attempted all the recommended suggestions. From adjusting camera positioning to calling the render function and setting ambient light, I've tried everything mentioned in forums but noth ...

Is HTML unable to display decoded %3C?

Two blocks of code with different input strings yield different results: // This does not change HTML var str = "%3Cdiv%3E"; // <div> var str_dec = decodeURIComponent(str); console.log(str_dec); // Console output is `<div>` document.getEleme ...

Is there a way to access the pixel data of a scene in Three.js without having to render it on the canvas?

Is there a way to obtain the pixel data (in the form of an array buffer) that would be displayed on a canvas if I were to render a scene, without actually rendering it on the canvas? If so, how can this be achieved? I have not written any code for this ye ...

Is it possible to customize the color of icons in react's Material-table?

I'm currently utilizing the material-table library and I'm struggling to individually change the color of each icon. Could you assist me with this? I attempted custom CSS, but it's affecting all icons at once instead of specific ones. Here i ...

Exploring Google Maps with Angular 5 Search Feature

I am a novice with Angular and have recently begun developing an Angular web application that includes Google Maps functionality. I am looking to add a search bar for autocomplete, where relevant places are displayed as soon as the user begins typing. Wh ...

What is the proper way to convert the date and time of Friday, October 23, 2015 at midnight into a specific format for a datetime string?

I'm currently utilizing the bootstrap datetimepicker and I need to retrieve the datetime and then add days to it. var get_date_time = Friday, October 23rd 2015, 12:00:00 am I want to format get_date_time to "Oct 25 2015 12:00:00 am", but I'm u ...

How can a JavaScript function be used to check a tag's status?

I currently have two select tags on my webpage. I want to ensure that only one option can be selected at a time from these two tags. If the user tries to select options from both tags, an error message should be displayed instructing them to choose only on ...

Establishing the initial state in React

Can someone help me with setting the default state in React? I'm working on a project that allows files to be dropped onto a div using TypeScript and React. I want to store these files in the state but I'm struggling with initializing the default ...

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 ...

The `col-md-4` element from Bootstrap 4 is not functioning properly within my ejs file

<div class="container"> <div class="row card-deck"> <% for(var i=0;i<campgrounds.length;i++){ %> <div class="card col-12 col-md-4"> <img class="card-image-top" src="<%= campgrounds[i].image %>" ...

Execute functions upon the completion of jQuery ajax requests

I need to trigger my function loadTest() once the bootstrap dialog is fully loaded and displayed. $(".btn").on("click", function() { $.ajax({ type: "POST", url: '/echo/html/', data: { html: '', ...

Navigating through intricate HTML structures with JavaScript can be challenging

Snippet of 01.js code: var childElements = document.getElementById('selected-plays').getElementsByTagName('li'); function getRequiredElements(childElements) { var listItems = []; var i = 0; for(i = 0 ; i < childElements. ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...

Top method for identifying discrepancies in 2 arrays of objects

I'm currently working with two arrays of objects and trying to find the most efficient way to compare them to identify any differences. https://i.sstatic.net/fIPnA.png I apologize for posting the image, but I felt it was necessary for better clarit ...

Retrieve data visualization tools from a separate function

Below is a Google dashboard featuring filtering, sorting, and paging functionality. I need to programmatically modify the sourceData and refresh the Google visualization from outside its containing function. The challenge is accessing the visualization fr ...

No defined parent for 'appendChild' operation

Seeking guidance on implementing a Solar System using THREE.js and encountering an issue: Error message: Cannot read property 'appendChild' of undefined Below is the current code snippet: <html> <head> <meta charse ...

Leverage Typescript to convert string literal types to uppercase

type x = 'first' | 'second' I am looking to create a type y that is similar to this: type y = 'FIRST' | 'SECOND' Here is what I attempted: type x = 'first' | 'second' type y = {[key in x]: key[& ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

Exploring JSON data in JavaScript

In my Json data, I have a nested structure of folders and files. My goal is to determine the number of files in a specific folder and its sub-folders based on the folder's ID. Below is an example of the JSON dataset: var jsonStr = { "hierarchy": ...