Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDK drag-n-drop auto scroll

I have an Angular 7 app, using CDK Drag-n-Drop to drag and drop rows in a very long list.

What should I do to allow the long list to auto scroll when the dragged item out of the current view?

Any sample code I can refer to?

like image 855
user2777473 Avatar asked Nov 07 '22 18:11

user2777473


1 Answers

I have faced the same issue, It happens anytime an outside element is scrollable. This is the open issue - https://github.com/angular/components/issues/16677. - I have slightly modified the solution mentioned in this link.

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;
      }
    });
  }
}

Template

 <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>
like image 124
rrr Avatar answered Nov 26 '22 12:11

rrr