需要手动在拖拽开始前更新cdkDragPreview
在组件中定义一个实例变量ref,然后在ngAfterViewInit中初始化ref,监听cdkDragStart事件,在该事件中调用updatePreview方法来更新cdkDragPreview。
示例代码:
import { Component, ElementRef, ViewChild } from '@angular/core';
import { CdkDragStart, CdkDragMove, CdkDragRelease } from '@angular/cdk/drag-drop';
@Component({
selector: 'app-draggable-component',
template: `
{{ data.name }}
{{ data.name }}
`,
styles: [
`
.item {
width: 100px;
height: 100px;
background-color: #ccc;
}
.preview {
position: absolute;
z-index: 1000;
background-color: #eee;
opacity: 0.5;
width: 100px;
height: 100px;
}
`,
],
})
export class DraggableComponent {
@ViewChild('preview') private preview: ElementRef;
private ref: HTMLElement;
data = { name: 'Drag me' };
constructor(private elementRef: ElementRef) {}
ngAfterViewInit() {
this.ref = this.elementRef.nativeElement.querySelector('.item').cloneNode(true);
this.preview.nativeElement.appendChild(this.ref);
}
onDragMoved(event: CdkDragMove) {
this.updatePreview(event);
}
updatePreview(event: CdkDragMove) {
this.ref.style.transform = `translate3d(${event.pointerPosition.x}px, ${event.pointerPosition.y}px, 0)`;
}
onDragStarted(event: CdkDragStart) {
this.updatePreview(event);
}
onDragReleased(event: CdkDragRelease) {
this.preview.nativeElement.removeChild(this.ref);
this.ref = null;
}
}