首页 > 解决方案 > 角度拖放图标到画布

问题描述

我需要角度拖放方面的帮助。就像我需要将图标拖到画布上一样。

我经历了很多例子,就是我所达到的例子。当我拖动该对象时,应该移动该对象的副本。我看过很多例子,请任何人帮助。

标签: javascripthtmlangulardrag-and-drop

解决方案


我们的“字段”是带有文本的对象,顶部和左侧。所以,你可以创建一个函数

changePosition(event:CdkDragEnd<any>,field)
  {
    console.log(field)
    field.top=+field.top.replace('px','')+event.distance.y+'px'
    field.left=+field.left.replace('px','')+event.distance.x+'px'
  }

然后你调用 .html

<div *ngFor="let field of fields;" cdkDrag (cdkDragEnded)="changePosition($event,field)"
          style="position:absolute;z-index:10" [style.top]="field.top" [style.left]="field.left">
                    {{field.text}}
            </div>

更新了问题,因为 Ananthakrishna 让我知道,您可以将拖放区中的一个元素拖出“dop-zone”

我们需要使用事件cdkDragDropped

<div *ngFor="let field of fields;" cdkDrag 
    (cdkDragDropped)="changePosition($event,field)"
     style="position:absolute;z-index:10" 
     [style.top]="field.top" 
     [style.left]="field.left">
        {{field.text}}
</div>

并且,在我们的函数 changePosition 中“检查”是否在 droppend 里面。我使用相关元素的 getBoundingClientRect :

changePosition(event:CdkDragDrop<any>,field)
  {
    
    const rectZone=this.dropZone.nativeElement.getBoundingClientRect()
    const rectElement=event.item.element.nativeElement.getBoundingClientRect()

    let top=+field.top.replace('px','')+event.distance.y
    let left=+field.left.replace('px','')+event.distance.x
    const out=top<0 || left<0 || 
              (top>(rectZone.height-rectElement.height)) || 
              (left>(rectZone.width-rectElement.width))
    if (!out) //If is inside
    {
       field.top=top+'px'
       field.left=left+'px'
    }
    else{ //we can do nothing
      this.fields=this.fields.filter(x=>x!=field) //or eliminate the object
    }
  }

查看分叉的stackblitz


推荐阅读