angular - How to use Angular7 (angular material) drag drop between two components
问题描述
As recently angular introduced drag and drop in angular material https://material.angular.io/cdk/drag-drop/overview .
All examples describes with in a single component. How to use this in two different components, Drag one component item and drop into another component.
解决方案
You may use properties id and cdkDropListConnectedTo to link both lists:
Component 1:
<div cdkDropList id="list-1" cdkDropListConnectedTo="list-2" (cdkDropListDropped)="drop($event)">
<div *ngFor="let item of list" cdkDrag>{{ item }}</div>
</div>
Component 2:
<div cdkDropList id="list-2" cdkDropListConnectedTo="list-1" (cdkDropListDropped)="drop($event)">
<div *ngFor="let item of list" cdkDrag>{{ item }}</div>
</div>
If you need to connect several lists to one list, you may use the following syntax: [cdkDropListConnectedTo]="['list-1', 'list-2', 'list-3', 'list-4']"
After linking the lists, you must correctly update one or both lists depending on the actions. You may do it on the drop function like this:
drop(event: CdkDragDrop<string[]>) {
if (event.container.id === event.previousContainer.id) {
// move inside same list
moveItemInArray(this.list, event.previousIndex, event.currentIndex);
} else {
// move between lists
}
}
For moving items between lists, you will possibly want to keep track of the lists centrally. You may do so by using a Service, a Store or other methods.
推荐阅读
- node.js - 如何在 Typescript 项目中使用 Node 16 中的计时器/承诺?
- python - 我正在尝试从 opencv 读取视频,但每次使用 cv2.imshow 或 imread 时都会出错
- python - 如何在处理字典的函数中处理重复的代码块?
- vue.js - NUXTJS 与 Store Getters 共享 JS 方法
- json - 使用 FTP 打开子文件夹时无法加载数据库服务器
- ubuntu - 在 ubuntu 实例上运行 cypress 时问号而不是特殊字符
- sql - Snowflake retrieving data of past month on a particular date of current month
- r - 如何确定哪些列没有可变性
- laravel - Dotenv\Dotenv::__construct() 必须是 Dotenv\Loader 的实例
- python - 使用状态(位置)作为条件的模糊匹配名称