1
votes

For some reason in Angular 9 placing a CDK drag on a mat dialog title div it will make the entire dialog draggable. This will prevent users from selecting text within the dialog box.

In Angular 7 you could only drag the dialog by actually dragging the div that you placed the cdk drag property in.

Is there any way to make the drag action happen only on the title of a mat dialog in Angular 9?

<h1 mat-dialog-title cdkDrag cdkDragRootElement=".cdk-overlay-pane" cdkDragHandle>
  <mat-icon>drag_handle</mat-icon>

  {{title}}
</h1>

<div mat-dialog-content>
  <p>{{message}}</p>
</div>

<div mat-dialog-actions>
  <button mat-button (click)="onDismiss()">No</button>
  <button mat-raised-button color="primary" (click)="onConfirm()">Yes</button>
</div>

I downloaded the code from this site https://onthecode.co.uk/how-to-make-angular-material-dialog-draggable-with-cdkdrag/

2
did you try to make a div around the code and handle the drag magic there? - Argee

2 Answers

2
votes

it's only enclose all the dialog in a div with cdkDrag, and add to h1 cdkDragHandle

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

See stackblitz

0
votes

The other answer did not work for me so I ended up creating a directive:

import { Directive, HostListener, AfterViewInit, ElementRef } from '@angular/core';

@Directive({
  selector: '[selectableTextInCdkDrag]'
})
export class SelectableTextInCdkDragDirective implements AfterViewInit {
  constructor(private elementRef: ElementRef) { }

  @HostListener('mousedown', [ '$event' ]) onMouseDown($event: Event): void {
    $event.stopPropagation();
  }

  @HostListener('touchstart', [ '$event' ]) onTouchStart($event: Event): void {
    $event.stopPropagation();
  }

  ngAfterViewInit(): void {
    this.elementRef.nativeElement.style['user-select'] = 'text';
    this.elementRef.nativeElement.style['cursor'] = 'initial';
  }
}

<div
  cdkDrag
  cdkDragHandle
  cdkDragBoundary=".cdk-global-overlay-wrapper"
  cdkDragRootElement=".draggable-dialog"
  class="draggable-dialog-content"
>
  <h1 selectableTextInCdkDrag>...</h1>
  <ul selectableTextInCdkDrag>...</ul>
</div>