I’m developing a table using Angular Material where user can also select the rows using checkboxes. So far the logic is working fine when the table has all data and changing of pagination doesn’t effect the selections. But when I moved to server side pagination, the dataSource
has become dynamic and the checkbox selections not rendering in view again when going back to the previous/next page that have the rows selected. I’ve checked that the selection.selected
is holding the value even on page change but why it’s not showing in view that’s the question.
private setupCheckboxIfPageChange() {
console.log(1);
const selected: TestTable[] = this.selection.selected;
this.selection.clear();
this.selection.select(...selected);
}
This function I’ve written & called in the API subscription. This is the example of what I tried.
2
Answers
It does not work because
SelectionModel
uses strict equality (===
) by default, and you are storing objects in the model. When working with two separate objects returned by different API calls, they will never be equal, even if all properties are the same. To avoid this issue, you should store only the IDs of the selected items in the selection model instead. It will also make your app faster, as less data is stored in-memory.Updated Stackblitz: https://stackblitz.com/edit/stackblitz-starters-gxci92
If you need the selection model to hold the whole object, check the other answer.
You can add in ngOnInit()
else, as the objects are differents the result are false