我正在尝试使用新的Angular 7 CDK拖放来移动元素列表。但是没有找到交换元素的任何选择,大部分给出的示例都是对元素进行排序的。
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);
}
}
例如:如果元素0的拖动操作已开始并拖放到元素4,则在这种情况下,元素0 dom应替换为元素4,反之亦然。
答案 0 :(得分:2)
您可以简单地手动交换项目:
drop(event: CdkDragDrop<string[]>) {
let oldtarget = this.movies[event.previousIndex];
this.movies[event.previousIndex] = this.movies[event.currentIndex];
this.movies[event.currentIndex] = oldtarget;
}
答案 1 :(得分:0)
答案 2 :(得分:0)
请查看此工作demo。