Objective: Create a table using Angular Material that can be modified using Angular Drag & Drop.
Expected Behavior: Table should re-order on drag-drop
Current Behavior: Rows are draggable, and the order of the underlying data source changes, but when the row is dropped it snaps back to its original position in the table.
See this example:
https://stackblitz.com/edit/drag-drop-reorder-mattable
How can this be fixed/implemented?
(Also, I'm not sure why it's styled so poorly in Stackblitz. Any insight there would also be appreciated)
Edit: I found a super hacky way to get the rows to render again with the correct order, but there's no way this is the way it's expected to be implemented. I just put t.renderRows() to be executed after the drop event handler. See full line below
<mat-table #t
cdkDropList
(cdkDropListDropped)="onListDrop($event); t.renderRows()"
[dataSource]="dataSource"
class="mat-elevation-z8">
...
</mat-table>
EDIT 2: I've done a simple refactor to use rxjs, and the first drag-drop reorder for each element works great. But when I attempt to move an element that has already been moved once, I don't get the expected behavior. Stackblitz app has been updated.
You are encountering angular/material2 issue #14056 "cdkDropList: event.previousIndex does not update on second move". A workaround of deepcloning the datasource is detailed in the issue and it's comments.
Take a look here where I play with your demo after a small change to the console log (console.log(`Moving item[${event.previousIndex}] "${this.items[event.previousIndex]}" to index ${event.currentIndex}`))
I drag "Item 0" from index 0 to index 3. The item at index 0 moves to index 3. ✔️
I drag "Item 0" from index 3 to index 1. The item at index 0 moves to index 1. ✖️
I drag "Item 0" from index 3 to index 2. The item at index 0 moves to index 2. ✖️
The event.previousIndex erroneously remains the same for a row after it has been moved to a different index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With