user2777473
user2777473

Reputation: 3826

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?

Upvotes: 8

Views: 10857

Answers (2)

Mohammad Rafigh
Mohammad Rafigh

Reputation: 796

As mentioned here you just need to add cdkScrollable to your list container.

Upvotes: 3

Renjith P N
Renjith P N

Reputation: 4251

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>

Upvotes: 1

Related Questions