Drag And Drop Images From Your Computer To Angular 8 Web Application

In today’s article, we will see how to drag and drop images from your computer to an Angular 8 web application using our custom directive.
 

Why do we need this?

 
In today’s world, almost all of the web applications have to deal with images on some level. Usually, the application provides a way to upload images but for better user experience, selecting multiple images at once and performing a drag and drop operation to your web application is a very common feature these days.
 
Let’s get started.
 
Open cmd at the location where you want to create your Angular project and enter the following command
 
ng new ImageDragDrop
 
Drag And Drop Images From Your Computer To Angular 8 Web Application
 
Once the creation of the project is done, open it up with your favorite editor (VS Code in my case)
 
Now we will create our new component in which we will implement the drag and drop feature.
 
For that run this command in the terminal:
 
ng g c image-upload
 
Drag And Drop Images From Your Computer To Angular 8 Web Application
 
After the execution of this command, you will see a folder generated with image-upload name
 
Drag And Drop Images From Your Computer To Angular 8 Web Application
 
Now we will go to app.component.html, delete everything on that file and just add the selector of your newly-generated component.
 
<app-image-upload></app-image-upload>
 
Drag And Drop Images From Your Computer To Angular 8 Web Application
 
Now let’s run our project. In the root folder of our project let’s run the command:
 
ng serve
 
When it runs completely, go to our browser and open the following URL:
 
http://localhost:4200
 
Drag And Drop Images From Your Computer To Angular 8 Web Application
Now let us create a directive. We will run this following command in the terminal:
 
ng g d ImageDrag
 
After the execution of the following command, you will see these two files:
 
Drag And Drop Images From Your Computer To Angular 8 Web Application
 
Now we will add an interface that will look something like this:
 
Drag And Drop Images From Your Computer To Angular 8 Web Application
 
Now we will modify our ImageDrag directive according to our functionality:
 
With the help of @HostListner we will add three events to our directive
  • dragover
  • dragleave
  • drop 
We will also have an output property that will emit the array of dropped files.
 
Our directive will look something like this,
  1. import {  
  2.     Directive,  
  3.     HostListener,  
  4.     EventEmitter,  
  5.     Output,  
  6.     HostBinding,  
  7. } from '@angular/core';  
  8. import {  
  9.     FileHandle  
  10. } from './file-handle';  
  11. import {  
  12.     DomSanitizer  
  13. } from '@angular/platform-browser';  
  14. @Directive({  
  15.     selector: '[appImageDrag]',  
  16. })  
  17. export class ImageDragDirective {  
  18.     @Output('files') files: EventEmitter < FileHandle[] > = new EventEmitter();  
  19.     @HostBinding('style.background'public background = '#eee';  
  20.     constructor(private sanitizer: DomSanitizer) {}  
  21.     @HostListener('dragover', ['$event']) public onDragOver(evt: DragEvent) {  
  22.         evt.preventDefault();  
  23.         evt.stopPropagation();  
  24.         this.background = '#999';  
  25.     }  
  26.     @HostListener('dragleave', ['$event']) public onDragLeave(evt: DragEvent) {  
  27.         evt.preventDefault();  
  28.         evt.stopPropagation();  
  29.         this.background = '#eee';  
  30.     }  
  31.     @HostListener('drop', ['$event']) public onDrop(evt: DragEvent) {  
  32.         evt.preventDefault();  
  33.         evt.stopPropagation();  
  34.         this.background = '#eee';  
  35.         let files: FileHandle[] = [];  
  36.         for (let i = 0; i < evt.dataTransfer.files.length; i++) {  
  37.             const file = evt.dataTransfer.files[i];  
  38.             const url = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(file));  
  39.             files.push({  
  40.                 file,  
  41.                 url  
  42.             });  
  43.         }  
  44.         if (files.length > 0) {  
  45.             this.files.emit(files);  
  46.         }  
  47.     }  
  48. }   
Here in drop event, we are just getting the files from DragEvent, and in order to show their preview, we are using DomSantizer to obtain their URL to show in img tags.
 
Now in order to use this, we will go back to our ImageUpload component, open its HTML file and place  this piece of code there,
  1. <div    
  2.    style="width: 500px; height: 250px; text-align: center;"    
  3.    appImageDrag    
  4.    (files)="filesDropped($event)"    
  5. >  
  6.     <span style="font-size: 25px;">Drop your files here</span>  
  7. </div>  
  8. <div style="margin-top: 20px; width: 500px; height: 400px;">  
  9.     <div *ngFor="let file of uploadedFiles">  
  10.         <img [src]="file.url" style="width: 100px; height: 100px;" />  
  11.     </div>  
  12. </div>     
Now we will go to its component file and modify it accordingly,
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     FileHandle  
  7. } from '../file-handle';  
  8. @Component({  
  9.     selector: 'app-image-upload',  
  10.     templateUrl: './image-upload.component.html',  
  11.     styleUrls: ['./image-upload.component.css'],  
  12. })  
  13. export class ImageUploadComponent implements OnInit {  
  14.     uploadedFiles: FileHandle[];  
  15.     constructor() {}  
  16.     ngOnInit(): void {}  
  17.     filesDropped(files: FileHandle[]) {  
  18.         this.uploadedFiles = files;  
  19.     }  
  20. }   
Now let’s run our application
 
Drag And Drop Images From Your Computer To Angular 8 Web Application
 

Summary

 
In today’s article, we have seen how we can drag and drop images from our local computer to our angular 8 web application using our own custom directive.
 
If you wish to see the code please click here!