angularangular-materialdrag-and-dropangular-cdkangular-cdk-drag-drop

MatDialog drag and drop with newest angular version


I like to implement DragAndDrop in my MatDialog.

For older Versions of Angular, like Angular 7, there is a solution, but for Angular 17 for Example, this solution doesn't work the same.

For Angular 7 the solution is the following:

You can simply use cdkDrag directive from @angular/cdk/drag-drop

dialog.html

<h1 mat-dialog-title 
   cdkDrag
   cdkDragRootElement=".cdk-overlay-pane" 
   cdkDragHandle>
     Hi {{data.name}}
</h1>

Here is a Stackblitz Example for Angular 7

The important thing is that the drag functionality only triggers if i click and move on the title of the dialog.

When i implement this solution for Angular 17 the drag functionality triggers if i click and move anywhere on the dialog, even the dialog content.

Here is a Stackblitz Example for Angular 17

NOTE: Sorry, I used StackBlitz the first time for my self. When I test my StackOverflowQestion here, this StackBlitz reports an error. But if I click then in the URL field of the browser and hit enter, it loads the StackBlitz. Dont know why it is like that.

This behaviour is bad, because on mobile devices if i have scrollable content in the dialog, this content is not scrollable anymore. Instead on trying to scroll, the DragAndDrop is triggered.

Is there any way to implement a solution, that this DragAndDrop for MatDialog with Angular 17 will only be triggered when i click and move on the dialog title?


Solution

  • You are missing the import for CdkDragHandle import, this caused the functionality to not work.

    Since Angular 7 is modular, we imported the entire DragDropModule module, which contained all the directives. But in latest angular (for standalone components), we have to add the directive imports individually or we can import the DragDropModule completely.

    @Component({
      selector: 'dialog-content-example-dialog',
      templateUrl: './dialog-content-example-dialog.html',
      standalone: true,
      imports: [
        MatDialogModule, 
        MatButtonModule,
        CdkDragHandle,  // <- changed here!
        CdkDrag
      ],
    })
    export class DialogContentExampleDialog {}