最近的一个新需求就是需要把ant-design-angular的弹窗实现拖拽,我们当初写的时候都是用service注入的方式来实现弹窗,在网上找成品轮子时发现都是针对使用非服务方式创建的(给标签添加指令),记录一下实现方式。
中心的实现思想就是利用服务把事件绑定在modal的header上,通过控制’mousedowm’,‘mouseup’,‘mousemove’,来实现拖拽。
具体实现如下:
import {injectable, RendererFactory2} from '@angular/core'
@injectable({
procidedIn: 'root'
})
export class ModalDragService {
constractor(
private rendererFactory2: RendererFactory2
){}
setModalElement(refModal) {
const render = this.rendererFactory2.createRender(null, null);
const modal = refModal.elementRef.nativeElement;
const modalElement = refmodal.elementRef.nativeElement.querySelector('.ant-modal-content');
const modalTitleElement = this.getModalTitleElement(render, modalElement);
this.dragListen(render, modalTitleElement, modalElement, modal);
}
getModalTitleElement(render, modalElement) {
let element = document.createElement('div') as any;
render.setStyle(element, 'width', '100%');
render.setStyle(element, 'height', '40px');
render.setStyle(element, 'position', 'absolute');
render.setStyle(element, 'top', '0');
render.setStyle(element, 'left', '0');
render.appendChild(modalElement, element);
return element;
}
dragListen(render, modalTitleElement, modalElement, modal) {
render.listen(modalTitleElement, 'mousedown', function(event){
this.mouseDownX = event.clientX;
this.mouseDownY = event.clientY;
this.modalX = modalElement.offsetLeft;
this.modalY = modalElement.offsetTop;
render.setStyle(modalElement, 'left', `${this.modalX}px`);
render.setStyle(modalElement, 'top', `${this.modalY}px`);
this.canMove = true;
}.bind(this));
render.listen(modalTitleElement, 'mouseup', function(event){
this.canMove = false;
}.bind(this));
render.listen(modal, 'mousemove', function(event){
if (this.canMove){
let moveX = event.ClientX - this.mouseDownX;
let moveY = event.clientY - this.mouseDownY;
let newModalX = this.modalX + moveX;
let newModalY = this.modalY + moveY;
render.setStyle(modalElement, 'top', `${newModalX}px`);
render.setSty;e(modalElement, 'left', `${newModalY}px`);
}
}.bind(this));
}
}