可以使用animationEnd事件来检测CSS过渡的结束,然后在回调函数中执行相关操作。以下是示例代码:
HTML:
Drag me!
TS:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { CdkDragEnd } from '@angular/cdk/drag-drop';
@Component({
selector: 'app-drag-example',
templateUrl: './drag-example.component.html',
styleUrls: ['./drag-example.component.scss']
})
export class DragExampleComponent implements OnInit {
@ViewChild('dragItem') dragItem: ElementRef;
ngOnInit() {
const item = this.dragItem.nativeElement;
if (!item) {
return;
}
item.addEventListener('animationend', (e: AnimationEvent) => {
if (e.animationName === 'cdk-drag-placeholder') {
// Place your code here, the animation is finished
}
});
}
onDragEnded(event: CdkDragEnd) {
const item = event.source.element.nativeElement;
// Reset the animation
item.classList.add('cdk-drag-placeholder');
item.style.transform = 'translate3d(0, 0, 0)';
item.addEventListener('animationend', (e: AnimationEvent) => {
if (e.animationName === 'cdk-drag-placeholder') {
// Place your code here, the animation is finished
}
});
}
}
请注意,在HTML中我们使用了“cdkDragReleased”代替默认事件,以在释放拖动项时调用“onDragEnded”函数。在函数中,我们需要重置动画并添加“animationend”事件侦听器来检测过渡的结束。同样,在ngOnInit中,我们检测元素上的“animationend”事件以处理完成动画时的操作。