angular drag and drop cdk doesn't work in angular material dialog

3.5k Views Asked by At

I want to change list order by drag and drop CDK of angular. It works on any page in my website, but when I use it inside a material dialog it doesn't work. When I drag a list item over another item, it doesn't change position on dragging over, also not on drop. Is there anything special to do to make it work inside the dialog?

simplest code that I am trying:

HTML

<div cdkDropList (cdkDropListDropped)="drop($event)">
  <div cdkDrag *ngFor="let n of numbers">
    {{n}}
  </div>
</div>

ts file

import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

numbers: number[]= [];

constructor() {
  this.n.push(2,3,4,5);
}

drop(event: CdkDragDrop<number[]>) {
  moveItemInArray(this.numbers, event.previousIndex, event.currentIndex);
}

app.module.ts

import { DragDropModule } from '@angular/cdk/drag-drop';

@NgModule({ imports: [..., DragDropModule]})

As I said, this code works in any place in any page, but when i copy it to dialog component it does not work

1

There are 1 best solutions below

2
On

Found a temporary solution (by @DeonduPreez) here:

https://github.com/angular/components/issues/15880#issuecomment-523476619

The idea is to keep the current scroll position before the dialog opens, then scroll to the top, then open the dialog, and lastly, after the dialog closes, scroll back to the saved location.

const doc = document.documentElement;
const left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);

if (top != 0 || left != 0) {
  window.scrollTo({ top : 0, left: 0 });
}
const modal: MatDialogRef = this.dialog.open(ModalComponent);
modal.afterClosed().subscribe(() => {
if (top != 0 || left != 0) {
    window.scroll({ top : top, left : left, behavior: "smooth" });
}
});