cdkDrag删除后如何获得位置?

Mic*_*ica 5 drag-and-drop draggable angular

嗨,我需要能够拖放一些html元素,但我需要知道放置的结束位置。

使用cdkDrag我从文档中看到的指令,有一个事件cdkDragEnded

这是我的模板:

<div cdkDrop>
  <div cdkDrag (cdkDragEnded)="dragEnd($event)">
    ...other stuff
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

回调是:

dragEnd(event: CdkDragEnd) {
  console.log(event);
}
Run Code Online (Sandbox Code Playgroud)

在控制台中,我找到了我需要的东西,但这是事件的私有属性,event.source._dragRef._passiveTransform并且在编译时收到错误消息。

您知道这些数据或其他我可以使用的东西是否以某种方式公开吗?

ego*_*hin 21

只需source.getFreeDragPosition()在这样的(getFreeDragPosition)事件中使用:

dragEnd($event: CdkDragEnd) {
    console.log($event.source.getFreeDragPosition());
}`

Run Code Online (Sandbox Code Playgroud)


Mic*_*ica 6

我找到的解决方案是检索设置的style.transformcdkDrag

import { Component, ViewChild, ElementRef } from "@angular/core";
import { CdkDragEnd } from "@angular/cdk/drag-drop";

@Component({
  selector: "item",
  styles: [
    `
      .viewport {
        position: relative;
        background: #ccc;
        display: block;
        margin: auto;
      }
      .item {
        position: absolute;
        background: #aaa;
      }
    `
  ],
  template: `
    <div class="viewport" cdkDrop>
      <div
        #item
        class="item"
        cdkDrag
        (cdkDragEnded)="dragEnd($event)"
        [style.top.px]="initialPosition.y"
        [style.left.px]="initialPosition.x"
      >
        anything
      </div>
    </div>
  `
})
export class CanvasItemComponent {
  constructor() {}

  @ViewChild("item")
  item: ElementRef;

  initialPosition = { x: 100, y: 100 };
  position = { ...this.initialPosition };
  offset = { x: 0, y: 0 };

  dragEnd(event: CdkDragEnd) {
    const transform = this.item.nativeElement.style.transform;
    let regex = /translate3d\(\s?(?<x>[-]?\d*)px,\s?(?<y>[-]?\d*)px,\s?(?<z>[-]?\d*)px\)/;
    var values = regex.exec(transform);
    console.log(transform);
    this.offset = { x: parseInt(values[1]), y: parseInt(values[2]) };

    this.position.x = this.initialPosition.x + this.offset.x;
    this.position.y = this.initialPosition.y + this.offset.y;

    console.log(this.position, this.initialPosition, this.offset);
  }
}
Run Code Online (Sandbox Code Playgroud)

或者:

dragEnd(event: CdkDragEnd) {
    this.offset = { ...(<any>event.source._dragRef)._passiveTransform };

    this.position.x = this.initialPosition.x + this.offset.x;
    this.position.y = this.initialPosition.y + this.offset.y;

    console.log(this.position, this.initialPosition, this.offset);
  }
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法可以在不使用私有变量的情况下获得转换 x 和 y 值?

编辑: 该功能将添加到https://github.com/angular/material2/pull/14696