Share with   

FILE DRAG AND DROP IN ANGULAR 10

How to create a drop zone area for drag and drop files to upload in angular.


Introduction

In this article, making own drop zone or drag and drop angular directive for supporting to upload files by drag and drop to dropzone area. We can drag and drop any type of files.

 

Prerequisite

1) Node js. Click here to install nodejs.

2) Angular Framework, If you do not know how to install angular in your system, please check this article install Angular

3) Bootstrap click here to install bootstrap.

 

Follow the below steps

1) Create Angular App

ng new file_drop_zone

This will create file_drop_zone angular project.

 

2) Open this app project in visual code or any other which is used by you.

 

3) Install all prerequisites packages for angular app

npm install bootstrap --save

In this project we don't need any 3rd party packages but for designing here we are using bootstrap framework for responsive template.

 

4) Go to src > angular.json file to register bootstrap in style, see below code.

// angular.json

"styles": [
   "src/styles.css",
   "node_modules/bootstrap/dist/css/bootstrap.css"
]

 

5) Create drag and drop directive in app by using this command

// make new directive

ng generate directive dropzone

 

This dropzone directive will auto register to main component declaration. If not registered in any module please register dropzone directive to app module or any module.

If you want to change the directive selector name then open the dropzone.directive.ts file you will find selector name like selector: '[appDropzone]'.

You can change this name appDropzone to your name like selector: '[DropZone]'.

 

6) Open DropZone Directive and add the below code

// dropzone.directive.ts

import { Directive, EventEmitter, HostBinding, HostListener, Output } from '@angular/core';

@Directive({
  selector: '[DropZone]'
})
export class DropzoneDirective {
  @Output() onFileDropped = new EventEmitter<any>();

  @HostBinding('style.opacity') private opacity = '1';
  @HostBinding('style.border') private border = 'none';

  @HostListener('dragover', ['$event']) public onDragOver(evt): any {
    evt.preventDefault();
    evt.stopPropagation();
    this.opacity = '0.8';
    this.border = 'dotted 2px #FF4D2A';
  }

  @HostListener('dragleave', ['$event']) public onDragLeave(evt): any {
    evt.preventDefault();
    evt.stopPropagation();
    this.opacity = '1';
    this.border = 'none';
  }

  @HostListener('drop', ['$event']) public ondrop(evt): any {
    evt.preventDefault();
    evt.stopPropagation();
    this.opacity = '1';
    this.border = 'none';
    const files = evt.dataTransfer.files;
    if (files.length > 0) {
      this.onFileDropped.emit(files);
    }
  }
}

This directive will handle the drag and drop files event. Host Listener method will helps to listen the events.

 

 @HostListener('drop', ['$event']) public ondrop(evt) :

This method will listen drop event in html. We can get files using this ondrop(evt) method call the dataTransfer.files. This will get all the files. Using @Output method in angular we can emit the the dropped files.

 

 @HostListener('dragleave', ['$event']) public onDragLeave(evt) :

This method will listen drag leave event in html. We can manage the drag leave method by changing behavior or styles etc.

 

 @HostListener('dragover', ['$event']) public onDragOver(evt) :

This method will listen drag over event in html. We can manage the drag over method by changing behavior or styles etc. When we drag over any files to drop zone area this will change the behavior by applying style or animation etc.

 

7) Use this DropZone directive to html bellow is example of file drag and drop handling.

Open app component html file to add some html and use of dropzone directive. and show uploaded files in table.

// app.component.html
<style>
   .dropzone{
      background-color: rgb(206, 206, 206);
      padding: 70px 50px;
   }
</style>

<div class="container text-center mt-5">
  <h3 class="mb-5"> Drop zone angular file drag and drop example. </h3>
  <!-- Apply DropZone Directive -->
  <div class="dropzone" DropZone (onFileDropped)="droppedFiles($event)">
    <div class="text-center">
      Drop files here.<BR>
      <span class="note needsclick">(This is just a demo dropzone. Selected
        files are <strong>not</strong> actually uploaded.)</span>
    </div>
  </div>
  <div class="file-table">
    <h3 class="m-3">List of Files</h3>
    <table class="table">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">File Name</th>
          <th scope="col">Size</th>
          <th scope="col">Type</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let file of allFiles; let i = index">
          <th scope="row">{{i+1}}</th>
          <td>{{file.name}}</td>
          <td>{{file.size}} Bytes</td>
          <td>{{file.type}}</td>
        </tr>
        <tr class="text-center" *ngIf="allFiles.length === 0">
          <td colspan="4"><strong>No files are uploaded</strong></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Add the file operation in app component.

// app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  allFiles: File[] = [];

  constructor() { }

  droppedFiles(allFiles: File[]): void {
    const filesAmount = allFiles.length;
    for (let i = 0; i < filesAmount; i++) {
      const file = allFiles[i];
      this.allFiles.push(file);
    }
  }
}

Run the application using command

ng serve

 

Check the results

 

We have successfully done with DropZone Drag and Drop File upload.

If you like please like and share to your developer friends.

 

Related Post :

Open model popup in Angular using @ng-bootstrap NgbModal

How to install angular in windows operating system.

Design student simple database using slick carousel implementation in angular with firebase.

How to install bootstrap 4 in angular application

Design custom bootstrap 4 pagination for angular project instead of using 3rd party pagination

How to install @ng-bootstrap to angular cli and uses of @ng-bootstrap

 

Author Image
Guest User

0 Comments