How to make angular material dialog draggable [dup

2019-08-05 15:21发布

This question already has an answer here:

Is it possible to make a Angular Material Dialog draggable? because after a loosing a lot of time for searching i didn't found a very clear answer.

1条回答
2楼-- · 2019-08-05 16:09

Yes and this was included in Angular Material version 7+ update, by using the cdkDragRootElement

Here's a sample copied from material.angular.io

HTML:

<button (click)="openDialog()">Open a draggable dialog</button>

<ng-template>
  <div class="example-dialog-content" cdkDrag cdkDragRootElement=".cdk-overlay-pane">
    Drag the dialog around!
  </div>
</ng-template>

TS:

export class CdkDragDropRootElementExample implements AfterViewInit, OnDestroy {
  @ViewChild(TemplateRef) _dialogTemplate: TemplateRef<any>;
  private _overlayRef: OverlayRef;
  private _portal: TemplatePortal;

  constructor(private _overlay: Overlay, private _viewContainerRef: ViewContainerRef) {}

  ngAfterViewInit() {
    this._portal = new TemplatePortal(this._dialogTemplate, this._viewContainerRef);
    this._overlayRef = this._overlay.create({
      positionStrategy: this._overlay.position().global().centerHorizontally().centerVertically(),
      hasBackdrop: true
    });
    this._overlayRef.backdropClick().subscribe(() => this._overlayRef.detach());
  }

  ngOnDestroy() {
    this._overlayRef.dispose();
  }

  openDialog() {
    this._overlayRef.attach(this._portal);
  }
}

Stackblitz: Draggable Dialog

查看更多
登录 后发表回答