During my attempt to use drag and drop functionality with Angular Material, I encountered an issue with updating the `pos` key in a JSON array. Specifically, I wanted to set the `pos` value to the value of `event.currentIndex` while also adjusting the position values of other items in the array.
component.ts
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
temp: number;
movies = [
{name: 'Episode I - The Phantom Menace', pos: 0},
{name:'Episode II - Attack of the Clones', pos: 1},
{name: 'Episode III - Revenge of the Sith', pos: 2},
{name: 'Episode IV - A New Hope', pos: 3}
];
drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.movies, event.previousIndex, event.currentIndex);
console.log(this.movies[event.currentIndex]);
console.log(this.movies);
this.temp = event.previousIndex;
event.previousIndex = event.currentIndex;
event.currentIndex = this.temp;
this.movies[event.currentIndex].pos = event.currentIndex;
this.movies[event.previousIndex].pos = event.previousIndex;
}
component.html
<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let movie of movies;" cdkDrag>
{{movie.name}} {{movie.pos}}
</div>
</div>
Initial list
https://i.sstatic.net/HSMWC.png
After swapping
https://i.sstatic.net/IqOlR.png
This issue occurs when dragging either the first or last item in the list.
What adjustments should be made to the code?