Angular 7拖放拖放交换元素

时间:2019-06-19 14:09:34

标签: angular drag-and-drop angular-material

我正在尝试使用新的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,反之亦然。

3 个答案:

答案 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;
}

Stackblitz example

答案 1 :(得分:0)

我不知道您是否真的检查过Angular Material文档,但是您可以从这里开始:

  

Angular docs (with a lot of sorting examples)

希望对您有所帮助;)

答案 2 :(得分:0)

请查看此工作demo