I'm trying to use the new Angular 7 CDK Drag and drop to move a list of elements. But didnt found any option to swap element mostly all the example given are for sorting elements.
https://stackblitz.com/angular/pxgqrvaqbxeg?file=app%2Fcdk-drag-drop-sorting-example.ts
cdk-drag-drop-sorting-example.htm
<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let movie of movies" cdkDrag>{{movie}}</div>
</div>
cdk-drag-drop-sorting-example.ts
import {Component} from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
/**
* @title Drag&Drop sorting
*/
@Component({
selector: 'cdk-drag-drop-sorting-example',
templateUrl: 'cdk-drag-drop-sorting-example.html',
styleUrls: ['cdk-drag-drop-sorting-example.css'],
})
export class CdkDragDropSortingExample {
movies = [
'Episode I - The Phantom Menace',
'Episode II - Attack of the Clones',
'Episode III - Revenge of the Sith',
'Episode IV - A New Hope',
'Episode V - The Empire Strikes Back',
'Episode VI - Return of the Jedi',
'Episode VII - The Force Awakens',
'Episode VIII - The Last Jedi'
];
drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.movies, event.previousIndex, event.currentIndex);
}
}
For eg: If drag for element 0 is initiated and dropped at element 4, in that case element 0 dom should be replaced with element 4 and vice versa.
You can simply swap the item manually:
drop(event: CdkDragDrop<string[]>) {
let oldtarget = this.movies[event.previousIndex];
this.movies[event.previousIndex] = this.movies[event.currentIndex];
this.movies[event.currentIndex] = oldtarget;
}
Stackblitz example
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