我有一个问题: 我想获取元素的位置作为值。例如,x = 10,y = 30。之后,我想使用它们下一次更新元素的位置。像首先一样,元素A在x = 5和y = 5的位置上。然后,我拖动位置并获得位置x = 10和y = 30。然后我设置下一次位置并更新位置。 请帮忙!
答案 0 :(得分:0)
这里an example on Stackblitz使用getBoundingClientRect()
来获取您需要的所有数据,下面是代码:
.ts:
import {
Component,
ElementRef,
ViewChild,
AfterViewInit,
AfterContentChecked,
AfterViewChecked
} from "@angular/core";
/**
* @title Basic Drag&Drop
*/
@Component({
selector: "cdk-drag-drop-overview-example",
templateUrl: "cdk-drag-drop-overview-example.html",
styleUrls: ["cdk-drag-drop-overview-example.css"]
})
export class CdkDragDropOverviewExample implements AfterViewChecked {
@ViewChild("block") block: ElementRef;
constructor() {}
ngAfterViewChecked() {
let datas = this.block.nativeElement.getBoundingClientRect();
console.log("datas = ", datas);
}
onDrop(item: any) {
console.log("item = ", item.target.getBoundingClientRect());
}
}
.html:
<div class="example-box" cdkDrag #block (mouseup)="onDrop($event)">
Drag me around
</div>
.css:
.example-box {
width: 200px;
height: 200px;
border: solid 1px #ccc;
}
请注意,这是使用Angular的cdkDrasg(我基于文档中的示例),因此如果您将其他功能用于拖放功能,则需要进行一些调整。
此外,您是否打算手动(通过打字稿)编辑位置,请考虑使用Renderer2
而不是直接使用ViewChild。