File Uploading with Drag & Drop on Angular

Burakcan Ekici
3 min readMar 16, 2020

Here is a sample to upload the file with drag and drop on Angular. How to make your own drag & drop area for file upload and how to customize by your desire are handled below. Also, the file(s) we want to upload can be selected with the button in the drag & drop area.

While dragging the files(s)

We are starting to create a drag & drop area for files. As you see in the pictures above, some changing happen when a file drags onto it. The area is becoming a bit darker and the color of the border that surrounds it is changing to green. Also, it contains a message and we make the “Select your file” part to clickable.

In app.component.html, we use div that covers input and label that use to select a file(s).

In app.component.css, we need to define the style of div and label that we mentioned above.

Style definitions for drag & drop area

After the definitions at left, the drag & drop looks like below;

To make the “Select your file” part clickable, we put it in a span tag a define it and define the style of label.

Style definitions for label

After the definitions at left, it becomes the following.

At app.component.html, we use the fileDragDrop directive, which I will explain below, to define what happens when the file(s) are dragged or dropped. To get dragged file(s), we use the (filesChangeEmitter) method and define it in the file-drag-n-drop.directive.ts file shown below. Also, we handle the style changing on the drag & drop area and the border in here by using decorators placed below.

  • HostBindings: it is used to change style properties when drag or drop operations are triggered.
  • HostListener: it is used to listen and attach the events we need to when drag or drop operations are triggered.

That’s it. As you see in the pictures below, selecting the file can be done in two ways.

  • When we drag anything over the area, we encounter the circumstances at left.
  • When we click the red button, the file browser is opened and we encounter the circumstances at right.

The source code is available here.

--

--