I'm trying to select pre-select some users in a table using Angular's selectionmodel. The call retrieving the users in the table and the call retrieving the already selected users are different so the actual objects are not the same.
I tried writing an equals method on the UserProfile class, this does not seem to change anything. Rewriting the code to use id's would fix the problem but i would like to have the selection model handling the actual objects instead of id's.
This is the code i'm using, but i hope my question is clear enough.
@Input() selected: UserProfile[];
ngOnInit() {
this.selection = new SelectionModel<UserProfile>(true, this.selected);
The
SelectionModelis implemented as a part of@angular/cdklibrary. The documentation can be found in the Collections page from Angular Material Documentation.In the code we use the following import:
The
SelectionModelis build using the native JavascriptSet()object, as can be found in the source code:The
Setobject lets you store unique values of any type, whether primitive values or object references.The implementation for
SelectionModelchecks if an item is contained in that set by usingSet.hasmethod.What we need to consider first is that, in Javascript, two different instances of objects are always not equal:
So, the following situation will arive:
More info about JS
Set()here.UPDATE (27.03.2023) - Angular 14+
From Angular 14, the
SelectionModelsupports a customcompareWithfunction - a function optionally passed in order to customize how theSelection Modeluniquely identifies the items:https://material.angular.io/cdk/collections/api#SelectionModel
So, we can compare our objects in the selection model by using their attributes (eg:
nameattribute). The compare functions returns a boolean:Initialize our
SelectionModelas follows:Stackblitz: https://stackblitz.com/edit/angular-ntmyut?file=src/app/selection-example/selection-example.component.ts
For Angular <=13:
There is no method to override the comparison method in the
Setobject, so I've wrote my own implementation of theSelectionModel-SelectionModelImmutableJSby using the very popular library called immutable-js. The implementation was inspired by the following answer.To simplify, by using
immutable-js, we'll have the following situation:The code for the Selection Model is a little bit too large and I will not post it inline - it can be found in the working demo.
In the app we'll use:
The full working demo: https://stackblitz.com/edit/angular-ivy-wnvohl