ngx-sortablejs: Wrong display order on Angular 9

Description

Only a single draggable div as follows:

<div [sortablejs]="selectedItems" [sortablejsOptions]="selectedItemsOptions">
    <button *ngFor="let item of selectedItems; let i = index;" [class.active]="item.isSelected" (click)="remove(item)">{{i + 1}}° {{item.label}}</button>
</div>

If an item is moved to the last position, when another item is addeded via code this.selectedItems.push(item) the list of items visualized is sorted wrongly. The array items order is correct, but the visual representation of it is not. I guess it’s some incompatibility between sortablejs/ngx-sortablejs and Angular 9, since if I try to reproduce the issue on a Angular 8 project it doesn’t happen.

How to reproduce

I uploaded a sample project here. The code is very simple, it’s just a new Angular application with changes on app.component.ts and app.component.html.

If you don’t want to download the sample you can just follow these steps:

  1. Create a new project with: ng new <project_name>
  2. Install dependencies: npm i -S ngx-sortablejs sortablejs npm i -D @types/sortablejs
  3. Import SortablejsModule in AppModule.ts
  4. Edit only app.component.ts and app.component.html according to the sample linked above.

Environment

I tested this on Angular 9.0.7 and Angular 8.2.14. Versions mentioned above are those indicated in <app-root ng-version="">. The issue shows up only on Angular 9.

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 12
  • Comments: 15

Most upvoted comments

Problem persists with:

  • Angular @ 11.2.3
  • ngx-sortablejs @ 11.1.0

Same problem here! Angular 10 with ngx-sortablejs 10.1.0.

A temporary solution is to use the onUpdate hook of the sortable-js options object and overwrite the sortablejs bindingTarget in it. This forces Angular’s change detection to run and re-render the ngFor correctly.

// We are in .ts component file
// For this example binding target is called "data"
 const sortablejsOptions = {
   onUpdate: () => {
      const originalData = {...this.data};
      this.data = {};
      setTimeout(() => {
         this.data = originalData;
      )}
   }
}

The data will then be rendered correctly.

Note: I also tried to omit the Angular2-Binding and use sortablejs directly with Angular, but this leads to the same problem. So maybe this problem is also/more related to the original sortablejs library.

I have the same issue. Any update on this?