如何在Material拖放中获取拖动项数据?

6

我正在学习Angular。我的第一个应用是待办事项清单。我试图使用Node.js和MongoDB来开发它。有三个容器:待办事项、正在进行和已完成。当我从待办事项中拖动一个项目到正在进行时,我想处理它的ID。我该怎么做?

      drop(event: CdkDragDrop<string[]>) {
        if (event.previousContainer === event.container) {
          moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
        } else {
          transferArrayItem(event.previousContainer.data,
                            event.container.data,
                            event.previousIndex,
                            event.currentIndex);
        }

              ///TODO handle dragged item id,title or someinformation


      }
1个回答

10
你可以像这样向可拖动项传递数据:

<div cdkDrag [cdkDragData]="todo" *ngFor="let todo of todos"></div>

在这种情况下,您的待办事项(todo item)数据将在事件对象中可用。
drop(event: CdkDragDrop<string[]>) {
  console.log(event.item.data);
} 

这就是我寻找了几个小时的东西。谢谢。 - Trinity
它对我不起作用,它说未定义。这是在事件项之后我得到的结果:CdkDrag {element: ElementRef, dropContainer: CdkDropList, _document: document, _ngZone: NgZone, viewContainerRef: ViewContainerRef, …} 数据中没有任何内容。 - Thorin
另一种方式是:event.previousContainer.data[event.previousIndex]。 - Thorin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接