首页 > 解决方案 > 想要拖动和替换元素而不是附加每个元素

问题描述

我想拖放元素的副本,但是每当我们拖动新元素时,它都应该替换旧元素。

    drop(event: CdkDragDrop<string[]>) {

    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);     
    } else {
      let item:any = event.previousContainer.data[event.previousIndex];
      let copy:any = JSON.parse(JSON.stringify(item));
      let element:any = {};
      for(let attr in copy){
        if(attr == 'title') {          
          element[attr] = copy[attr] += ' copy';
        } else{
          element[attr] = copy[attr];
        }       
      }

      this.destination.splice(event.previousIndex,0,element);  
     }
    }

堆栈闪电链接

标签: angular

解决方案


在你的 drop 函数中,只需替换

//this.destination.splice(event.previousIndex,0,element); //<--replace this
//by 
  this.destination=[element];

注意:如果您使用空的 cdkDragPlaceholder,您会感觉更好

在你的 originList

<div class="field-box" *ngFor="let item of origin" cdkDrag>{{item.title}}
    <!--add this line -->
      <div *cdkDragPlaceholder ></div>
</div>

推荐阅读