如何在两个组件之间使用Angular7(角度材料)拖放 [英] How to use Angular7 (angular material) drag drop between two components

查看:15
本文介绍了如何在两个组件之间使用Angular7(角度材料)拖放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近 Angular 在 Angular 材质中引入了拖放https://material.angular.io/cdk/drag-drop/overview.

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.

推荐答案

您可以使用属性 idcdkDropListConnectedTo 来链接两个列表:

You may use properties id and cdkDropListConnectedTo to link both lists:

组件 1:

<div cdkDropList id="list-1" cdkDropListConnectedTo="list-2" (cdkDropListDropped)="drop($event)">
    <div *ngFor="let item of list" cdkDrag>{{ item }}</div>
</div>

组件 2:

<div cdkDropList id="list-2" cdkDropListConnectedTo="list-1" (cdkDropListDropped)="drop($event)">
  <div *ngFor="let item of list" cdkDrag>{{ item }}</div>
</div>

如果需要将多个列表连接到一个列表,可以使用以下语法:[cdkDropListConnectedTo]="['list-1', 'list-2', 'list-3', 'list-4']"

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']"

链接列表后,您必须根据操作正确更新一个或两个列表.您可以像这样在 drop 函数上执行此操作:

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.

这篇关于如何在两个组件之间使用Angular7(角度材料)拖放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆