Drag and drop custom behavior

后端 未结 1 1167
长发绾君心
长发绾君心 2021-01-29 07:42

I try to implement this behavior http://jsfiddle.net/Aneeshmohan/qbxfbmtt/ in angular 8. I use angular cdk drag-drop module https://stackblitz.com/edit/angular-4ppaey?file=s

相关标签:
1条回答
  • 2021-01-29 08:03

    Razvan, I know the cdkDrag is talking always about List, but you needn't use a list. if our "items" has as properties top and left, we can draw in his position.

    You can have a drop zone like

    <div #dropZone class="dropZone" cdkDropList id="drop-list" 
           (cdkDropListDropped)="itemDropped($event)">
        <div *ngFor="let field of fields;" cdkDrag
               style="position:absolute;z-index:10" 
               [style.top]="field.top" 
               [style.left]="field.left">
               {{field.text}}
         </div>
    </div>
    

    And a list

       <div id="div1" cdkDrag cdkDropList 
            cdkDropListConnectedTo="drop-list" 
            *ngFor="let type of types"
            [cdkDragData]="type" (cdkDragMoved)="moved($event)">
            {{type.text}}
            <div *cdkDragPlaceholder class="field-placeholder"></div>
    
        </div>
    

    In move we store the position of the pointer

      moved(event: CdkDragMove) {
        this._pointerPosition=event.pointerPosition;
      }
    

    In dropped calculate the position

      itemDropped(event: CdkDragDrop<any[]>) {
        if (event.previousContainer === event.container) {
          moveItemInArray(this.fields, event.previousIndex, event.currentIndex);
        } else {
          event.item.data.top=(this._pointerPosition.y-this.dropZone.nativeElement.getBoundingClientRect().top)+'px'
          event.item.data.left=(this._pointerPosition.x-this.dropZone.nativeElement.getBoundingClientRect().left)+'px'
          this.addField({...event.item.data}, event.currentIndex);
        }
      }
    

    see the stackblitz

    For "don't desapear" I think that the only way is make a "fixed copy" behind the drag zone, some like this another answer in SO

    0 讨论(0)
提交回复
热议问题