import { Directive, ElementRef, HostListener, Inject, Input, } from '@angular/core'; import { DOCUMENT, } from '@angular/common'; @Directive({ selector: '[setDragImageToHtml]', }) export class SetDragImageToHtmlDirective { @Input('setDragImageToHtml') public elementToUseAsDragImage: ElementRef; @Input() public maxWidth = 200; public imageDragClone: HTMLElement; constructor( @Inject(DOCUMENT) private _document: Document, ) {} @HostListener('dragstart', ['$event']) public dragStart(dragEvent: Event) { this.imageDragClone = this.elementToUseAsDragImage .nativeElement.cloneNode(true); this.imageDragClone.style.maxWidth = `${this.maxWidth}px`; this._document.body.appendChild(this.imageDragClone); (dragEvent as DragEvent).dataTransfer.setDragImage( this.imageDragClone, this.imageDragClone.offsetWidth / 2, this.imageDragClone.offsetHeight / 2, ); } @HostListener('dragend') public dragEnd() { this._document.body.removeChild(this.imageDragClone); this.imageDragClone = null; } }