CdkDrag更新位置

时间:2019-10-17 13:25:51

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

我有多个CdkDrag元素,这些元素是从组件中数组上的ngFor循环渲染的。当我删除一个元素我拼接数组。然后,某些元素将在那里更新位置。我该如何避免?

我试图先删除所有可拖动元素的freeDragPosition,然后再删除其中之一,然后重置其位置,但这没有用。

这是我的app.component.html

<div class="container" id="container">
  <div *ngFor="let f of fields; let i = index;" 
    class="textField"
    [attr.data-guid]="f.guid"  
    (mouseenter)="onFieldHover($event)" 
    cdkDrag 
    cdkDragBoundary="#container"
    (cdkDragEnded)="onDragEnded($event)"
    [cdkDragFreeDragPosition]="f.position">
    <div class="textField-inner">
      <span style="color: hotpink; font-weight: bold">{{f.guid}}</span>
    </div>
    <div class="textField-options">
      <div class="textField-move" cdkDragHandle>
        <svg width="24px" fill="currentColor" viewBox="0 0 24 24">
          <path d="M10 9h4V6h3l-5-5-5 5h3v3zm-1 1H6V7l-5 5 5 5v-3h3v-4zm14 2l-5-5v3h-3v4h3v3l5-5zm-9 3h-4v3H7l5 5 5-5h-3v-3z"></path>
          <path d="M0 0h24v24H0z" fill="none"></path>
        </svg>
      </div>
      <div class="textField-remove">
        <i class="fas fa-trash-alt" (click)="onRemoveTextField(i)"></i>
      </div>
    </div>
  </div>
</div>
<button type="button" (click)="onTextFieldAdded()">Add a field</button>

这是我的app.component.ts

import { Component } from '@angular/core';
import {CdkDrag, CdkDragEnd} from '@angular/cdk/drag-drop';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.scss' ]
})
export class AppComponent  {
  name = 'Angular';
  fields: Field[] = [];
    draggables: CdkDrag<any>[] = [];


  onDragEnded(event: CdkDragEnd){
        if(!this.draggables.find(f => f == event.source)){
            this.draggables.push(event.source);
        }
    }

  onFieldHover(event: any){
        if(event.target.classList.contains('initialPosition')){
            event.target.classList.remove('initialPosition');
            event.target.style.transform = "translate3d(250px, 180px, 0px)";
        }
    }

  onTextFieldAdded() {
        let field = new Field();
        field.index = this.fields.length;
        field.guid = this.newGuid();

        this.fields.push(field);
    }

  onRemoveTextField(index: number){
    let positions : any[] =[];

        this.draggables.forEach(drag => {
            let pos = { guid: drag.element.nativeElement.getAttribute("data-guid"), pos: drag.getFreeDragPosition()  };
            positions.push(pos);
            console.log(pos);
        });

        this.fields.splice(index, 1);

    positions.forEach(p => {
      let newPos = {x: p.pos.x, y: p.pos.y};
      console.log(newPos);
      this.fields.find(f => f.guid == p.guid).position = newPos;
        });
    }

  newGuid(): string{
     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
  }

}

export class Field{
    index: number;
    guid: string;
    position: {x: number, y: number}
}


当元素之一被删除时,我希望元素保留在当前位置。

这是代表问题的.gif element moving has i delete one

这是一次突击 https://stackblitz.com/edit/angular-p3yfe7

2 个答案:

答案 0 :(得分:3)

在您的堆栈闪电中进行了一些测试之后,我能够重现您的预期行为,结果是当cdkDrag位于ng内时,它会绑定到同一列表,并且当您从列表中删除一个cdkDrag时,它将呈现模板,但是新位置以匹配ngFor列表顺序,以避免您可以从cdkDrag覆盖css样式position

在您的示例中,只需将position: absolute;添加到.textField css类中即可。

答案 1 :(得分:0)

问题是您没有在trackBy中指定*ngFor函数,这将导致只要数组更改,对象就会重新呈现:

您应该这样创建*ngFor

*ngFor="let f of fields; let i = index; trackBy: trackByField"

并更新您的组件以使用trackByField方法

 trackByField = (i: number, field: Field) => field.guid;

然后,已经移动的项目将保留在原位置,而未移动的项目仍将重新排序

stack