返回

自定义ng-zorro11的modal组件可拖拽(模板创建的弹窗)

前端

前言

最近在项目中需要一个可拖拽的弹窗,网上搜索后发现大部分实现都是针对服务端创建的弹窗,而对于通过模板创建的弹窗,实现起来就比较困难。因此,我参考了其他人的实现并进行了改进,最终成功实现了一个基于模板创建的拖拽式modal组件。

实现步骤

1. 创建modal组件

首先,我们需要创建一个modal组件。在这个组件中,我们将定义模态窗口的结构和行为。

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss']
})
export class ModalComponent {

  @Input() title: string;
  @Input() content: string;

  constructor() { }

}

2. 在modal组件中添加拖拽功能

接下来,我们需要在modal组件中添加拖拽功能。为此,我们将使用Angular的拖放指令。

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

@Directive({
  selector: '[appDraggable]'
})
export class DraggableDirective {

  private _isDragging = false;
  private _initialX: number;
  private _initialY: number;
  private _currentX: number;
  private _currentY: number;

  constructor(private _elementRef: ElementRef) { }

  @HostListener('mousedown', ['$event'])
  onMouseDown(event: MouseEvent) {
    this._isDragging = true;
    this._initialX = event.clientX;
    this._initialY = event.clientY;
  }

  @HostListener('mousemove', ['$event'])
  onMouseMove(event: MouseEvent) {
    if (!this._isDragging) {
      return;
    }

    this._currentX = event.clientX;
    this._currentY = event.clientY;

    const deltaX = this._currentX - this._initialX;
    const deltaY = this._currentY - this._initialY;

    this._elementRef.nativeElement.style.left = `${this._elementRef.nativeElement.offsetLeft + deltaX}px`;
    this._elementRef.nativeElement.style.top = `${this._elementRef.nativeElement.offsetTop + deltaY}px`;
  }

  @HostListener('mouseup', ['$event'])
  onMouseUp(event: MouseEvent) {
    this._isDragging = false;
  }

}

3. 在modal组件的模板中添加拖拽指令

现在,我们需要在modal组件的模板中添加拖拽指令。

<div class="modal-header" appDraggable>
  <h4 class="modal-title">{{ title }}</h4>
  <button type="button" class="close" aria-label="Close" (click)="close()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

4. 在应用中使用modal组件

最后,我们需要在应用中使用modal组件。

<app-modal [title]="'Modal Title'" [content]="'Modal Content'"></app-modal>

总结

通过以上步骤,我们就成功地创建了一个可拖拽的modal组件,并通过模板创建弹窗,实现了拖拽功能。希望本文对您有所帮助。