Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 drag Drop swapping elements

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.

like image 251
raoul.nair Avatar asked Jun 19 '19 14:06

raoul.nair


1 Answers

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

like image 191
Shinjo Avatar answered Oct 19 '22 16:10

Shinjo