Angular 元素拖拽
-
拖动元素到指定区域
-
拖放的同时传递数据
1. 安装 ng2-drag-drop
npm install ng2-drag-drop --save
2. 模板中配置可拖拽元素
// drag.component.html
<div>
<a href="javascript:;" *ngFor="let item of sysData" draggable [dragData]="item" [dragScope]="'system'">{{ item.name }}</a>
</div>
-
draggable - 表明此元素时可拖拽的
-
[dragData] = 'item' - 在拖动过程中将item数据从draggable到droppable
-
[dragScope]="'system'" - 拖拽范围,和第三步[dropScope]="'system'"相对应;
3. 模板中配置拖拽元素所拖拽的目的地
// drag.component.ts
<div droppable (onDrop)="onItemDrop($event)" [dropScope]="'system'"></div>
-
droppable - 第二步中拖拽的元素都将拖拽到有droppable指令的元素内;
-
(onDrop) - 当拖拽元素至此区域内后(鼠标释放后),触发onItemDrop方法,其中$event就是第二步中[dragData] = 'item'的item参数
-
[dropScope]="'system'" - 和第二步的[dragScope]="'system'"对应,[dragScope]="'system'"的拖拽元素只能拖拽到 [dropScope]="'system'"元素内;
4. ts文件
// drag.component.ts
export class DragComponent {
const sysData = [
{id: '1', name: '拖动元素1'},
{id: '2', name: '拖动元素2'},
{id: '3', name: '拖动元素3'},
{id: '4', name: '拖动元素4'}
];
}
onItemDrop(e: any) {
// data为拖拽时传递的数据 - item
const data = e.dragData;
}
https://www.yuque.com/smallwhy?tab=books