首页 > 解决方案 > CDK拖放式自动滚动

问题描述

我有一个 Angular 7 应用程序,使用 CDK Drag-n-Drop 在很长的列表中拖放行。

当拖动项目离开当前视图时,我应该怎么做才能让长列表自动滚动?

我可以参考任何示例代码吗?

标签: drag-and-dropangular7autoscrollangular-cdk

解决方案


我遇到了同样的问题,只要外部元素可滚动,就会发生这种情况。这是未解决的问题 - https://github.com/angular/components/issues/16677。- 我稍微修改了此链接中提到的解决方案。

import { Directive, Input, ElementRef, AfterViewInit } from '@angular/core';
import { CdkDrag } from '@angular/cdk/drag-drop';

@Directive({
  selector: '[cdkDrag],[actualContainer]',
})
export class CdkDropListActualContainerDirective {
  @Input('actualContainer') actualContainer: string;
  originalElement: ElementRef<HTMLElement>;

  constructor(cdkDrag: CdkDrag) {
    cdkDrag._dragRef.beforeStarted.subscribe( () => {
      var cdkDropList = cdkDrag.dropContainer;
      if (!this.originalElement) {
        this.originalElement = cdkDropList.element;
      }

      if ( this.actualContainer ) {
        const element = this.originalElement.nativeElement.closest(this.actualContainer) as HTMLElement;
        cdkDropList._dropListRef.element = element;
        cdkDropList.element = new ElementRef<HTMLElement>(element);
      } else {
        cdkDropList._dropListRef.element = cdkDropList.element.nativeElement;
        cdkDropList.element = this.originalElement;
      }
    });
  }
}

模板

 <div mat-dialog-content class="column-list">
    <div class="column-selector__list">
      <div cdkDropList (cdkDropListDropped)="drop($event)">
        <div
          *ngFor="let column of data"
          cdkDrag
          actualContainer="div.column-list"
        >
        </div>
      </div>
    </div>
  </div>

推荐阅读