注意:以下示例代码基于Angular CDK v12.2.9版本。
在Angular CDK的v10版本中,拖放CDK包含了一些已被弃用的函数,如“enter”和“exit”。这些函数通常用于在拖动元素时处理容器的状态变化。在较新版本的Angular CDK中,可以使用DragDropRegistry类的register和deregister方法替代这些函数。
下面给出一个示例组件,使用register和deregister方法替代enter和exit函数。这个组件实现了一个列表,其中的元素可以通过拖拽方式重新排序。
import { Component, OnInit, OnDestroy } from '@angular/core'; import { CdkDragDrop, DragDropRegistry } from '@angular/cdk/drag-drop'; import { Subscription } from 'rxjs';
@Component({
selector: 'app-draggable-list',
template:
})
export class DraggableListComponent implements OnInit, OnDestroy {
items = ['Item 1', 'Item 2', 'Item 3'];
connectedDropListId = 'connectedDropListId';
registry: DragDropRegistry;
subscription: Subscription;
constructor(registry: DragDropRegistry) { this.registry = registry; }
ngOnInit() { this.subscription = this.registry.getDropContainer(this.connectedDropListId) .connect() .subscribe(drag => { // 通过拖动来更新列表元素的顺序 const prevIndex = this.items.indexOf(drag.item.data); const newIndex = drag.currentIndex; this