Created
March 8, 2020 11:37
-
-
Save AnteaterKit/c47b5db9c96b1cbc397629060b831e64 to your computer and use it in GitHub Desktop.
angular drag and drop file directive #2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'; | |
@Directive({ | |
selector: '[appAsFileDrop]' | |
}) | |
export class AsFileDropDirective { | |
private element: HTMLElement; | |
constructor(private elementRef: ElementRef, private renderer: Renderer2) { | |
this.element = elementRef.nativeElement; | |
} | |
@HostListener('drop', ['$event']) | |
public onDrop(event: any): any { | |
const files = event.dataTransfer.files; | |
if (!files || files.length === 0) { | |
return; | |
} | |
const imgElement = this.renderer.createElement('img'); | |
imgElement.file = files[0]; | |
this.renderer.appendChild(this.element, imgElement); | |
const fileReader = new FileReader(); | |
fileReader.onload = (ev) => { | |
imgElement.src = ev.target.result; | |
}; | |
fileReader.readAsDataURL(files[0]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment