在Angular7中如何創(chuàng)建拖放列表?

我們可以使用angular Component Development Kit(CDK)提供的Drag-Drop模塊輕松創(chuàng)建待辦事項列表。
首先,使用以下命令創(chuàng)建角度分量:
ng g c To-Do現(xiàn)在,從@ angular / cdk / drag-drop導入CdkDragDrop,moveItemInArray,transferArrayItem到我們的待辦事項組件,
為組件視圖編寫代碼:
創(chuàng)建兩個分區(qū),一個分區(qū)用于“待完成”項目,另一個分區(qū)用于“已完成”項目。
參數(shù)如下:
cdkDropList:它是一個放置容器。
cdkDropListData:它將數(shù)據(jù)綁定到視圖。
cdkDropListConnectedTo:獲取當前分區(qū)連接到的另一個放置容器的ID。
cdkDropListDropped:拖動項目后,必須更新數(shù)據(jù)模型。
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”列表。
本文完~

評論
圖片
表情
