在Angular7中如何创建拖放列表?

我们可以使用angular Component Development Kit(CDK)提供的Drag-Drop模块轻松创建待办事项列表。
首先,使用以下命令创建角度分量:
ng g c To-Do现在,从@ angular / cdk / drag-drop导入CdkDragDrop,moveItemInArray,transferArrayItem到我们的待办事项组件,
为组件视图编写代码:
创建两个分区,一个分区用于“待完成”项目,另一个分区用于“已完成”项目。
参数如下:
cdkDropList:它是一个放置容器。
cdkDropListData:它将数据绑定到视图。
cdkDropListConnectedTo:获取当前分区连接到的另一个放置容器的ID。
cdkDropListDropped:拖动项目后,必须更新数据模型。
cdkDrag:它指定可以拖动的项目。
例子:
<div><!-- container for both list --><h1>To do</h1><!-- To-Do list --><divcdkDropList#todoList="cdkDropList"[cdkDropListConnectedTo]="[doneList]"[cdkDropListData]="todo"(cdkDropListDropped)="drag($event)"><div *ngFor="let item of todo" cdkDrag>{{item}}</div></div></div><div><h1>Done</h1><!-- Done list --><divcdkDropList#doneList="cdkDropList"[cdkDropListConnectedTo]="[todoList]"[cdkDropListData]="done"class="example-list"(cdkDropListDropped)="drag($event)"><div *ngFor="let item of done" cdkDrag>{{item}}</div></div></div>
在这里,我们使用了一个硬编码的列表,但是你始终可以使用ngmodel指令进行输入。
将项目拖到同一容器中:使用moveItemInArray将其移动到同一容器中 将项目拖到另一个容器:使用transferArrayItem移到另一个容器中。
export class To-Do {// hardcoded liststodo = ['Go to gym','Eat lunch','Take a nap','Physics syllabus'];done = ['Assignment','Coding practice','Maths syllabus','English syllabus'];//function for listening to the eventdrag(event: CdkDragDrop<string[]>) {//if movement if within the same containerif (event.previousContainer === event.container) {moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);}//if movement if to other containerselse {transferArrayItem(event.previousContainer.data,event.container.data,event.previousIndex,event.currentIndex);}}}

我们成功的将“Eat lunch”从“To do”列表拖到“Done”列表。
本文完~

评论
