Last active
January 31, 2020 14:00
Angular2 clipboard paste event
This file contains 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
<textarea placeholder="Type a message" (paste)="onPaste($event)"></textarea> | |
<!-- Place to render the image --> | |
<img #imgRenderer /> |
This file contains 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
// Reference to the dom element | |
@ViewChild('imgRenderer') imgRenderer: ElementRef; | |
onPaste(event: any) { | |
const items = (event.clipboardData || event.originalEvent.clipboardData).items; | |
let blob = null; | |
for (const item of items) { | |
if (item.type.indexOf('image') === 0) { | |
blob = item.getAsFile(); | |
} | |
} | |
// load image if there is a pasted image | |
if (blob !== null) { | |
const reader = new FileReader(); | |
reader.onload = (evt: any) => { | |
console.log(evt.target.result); // data url! | |
this.imgRenderer.nativeElement.src = evt.target.result; | |
}; | |
reader.readAsDataURL(blob); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment