Search code examples
angularjsvmware-clarity

Datagrid selection get lost ramdomly


I am using VMWare Clarity datagrid with single selection.

Behind the scene, I am receiving updated data and randomly, the selected row is no more selected.

I found those links where they seemed to have the same issue and looks like it is fixed in 0.12.2, but I don't see that from side:

https://github.com/vmware/clarity/issues/484

https://github.com/vmware/clarity/issues/2342

Here my code

html

<clr-datagrid [clDgRowSelection]="true" [(clrDgSingleSelected)]="selectedUnit">
   ...

   <clr-dg-row *clrDgItems="let unit of units" [clrDgItem]="unit" (click)="backupSelectedUnit(unit)">
      ...
   </clr-dg-row>
</clr-datagrid>

JS

myfunc() {

    this.units = this.getUpdatedUnits();
}

Thanks in advance


Solution

  • You are missing the trackBy on *clrDgItems. Whenever you are dealing with objects you receive from the server, you really want to make sure you are using trackBy to help Angular (and thus Clarity) know how to compare your objects. Otherwise the only comparison Angular can perform is reference equality, which isn't preserved when you keep getting updated objects from the server. Here is the official documentation for it, and you can find a maybe more readable explanation in the template syntax docs.

    *clrDgItems supports the same trackBy option as *ngFor, so you can just write:

    <clr-dg-row *clrDgItems="let unit of units; trackBy: trackById" ...>
    

    where trackById is a function you add to your component that looks like this:

    trackById = (index, unit) => unit.id
    

    I'm assuming here that the objects you receive from the server have an id, but you can use any other way to identify them depending on your specific use case.