【问题标题】:Angular CDK Drag & Drop: Don't move source itemAngular CDK 拖放:不要移动源项目
【发布时间】:2019-09-30 12:11:37
【问题描述】:

我正在尝试实现一个编辑器,可以在其中拖动项目以将其添加到主要内容中,问题是当我拖出源项目容器时源项目总是被破坏。

有没有办法强制源项目保持在原位,同时仍然可以拖放项目?基本上,我想要一个复制行为而不是移动行为。

我已经看到了与我基本上想要实现的目标相对应的其他问题,但它们都没有真正帮助我,因为这些问题更多的是关于如何在技术上完成复制项目,而我想知道我是如何做到的在 UI 中实现此行为,因为它非常难以查看项目是否刚刚消失。

【问题讨论】:

标签: angular drag-and-drop angular-cdk


【解决方案1】:

替换

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
    );
  }
}

drop(event: any) {
  if (event.previousContainer === event.container) {
    moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
  } else {
    copyArrayItem(
      event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex
    );
  }
}

【讨论】:

  • 感谢您的解决方案。但是,对于这种行为,在移动元素的列表中存在样式问题。它会在列表中波动,因为它看起来像是删除然后将元素添加到列表中以进行复制操作。请参考这个 stackblitz 链接 - stackblitz.com/edit/…
【解决方案2】:

导入import {copyArrayItem} from '@angular/cdk/drag-drop';

transferArrayItem 替换为copyArrayItem

【讨论】:

    【解决方案3】:

    您需要找到目标和源的位置,然后复制该值

    案例一:从一个可拖动列表复制到另一个可拖动列表

       drop(event: any) {
            if (event.previousContainer === event.container) {
                  moveItemInArray(
                    event.container.data,
                    event.previousIndex,
                    event.currentIndex
                  );
                } else {
    
                  const prev_idx = event.previousIndex;
                  const curr_id = event.currentIndex;
                  // Copy the data.
                  event.container.data[curr_id] = event.previousContainer.data[prev_idx];
            
                }
              }
        }
    

    案例 2:将数据从列表复制到特定变量

    drop(event: any) {
              // Copy the data to my-variable
                      const prev_idx = event.previousIndex;    
                      this.my-variable = event.previousContainer.data[prev_idx];
                
                    }
                  }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 2019-08-14
      相关资源
      最近更新 更多