Drag And Drop Image Upload In Angular

Introduction:

The drag-and-drop technique is a way to move computer files or images by clicking on them with the mouse and dragging them across the screen.

In this article, we will create a drop zone for uploading an image file in our angular project. Let’s start 🙂

Get Started:

Step 1: Install dependency.

Open your existing Angular application and install ngx-dropzone npm in it by running the following command.

npm i ngx-dropzone

Step 2: Import module in app.module.ts file.

.
.
import { NgxDropzoneModule } from 'ngx-dropzone';
.
.
  imports: [
    .
    .
    NgxDropzoneModule
  ],

Step 3: Add the following code to your app.component.ts file.

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

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

  onSelect(event: Event | any) {
    console.log(event);
    this.files = []; //Remove this line if you want to add multiple files
    this.files.push(...event.addedFiles);
  }

  onRemove(event: Event | any) {
    console.log(event);
    this.files.splice(this.files.indexOf(event), 1);
  }
}

Step 4: Add the following code to your app.component.html file.

<div class="main-container">
  <div class="custom-dropzone" ngx-dropzone [multiple]="false" [accept]="'image/*'" (change)="onSelect($event)">
    <!-- Remove [multiple]="false" if you want to add multiple files.  -->
    <ngx-dropzone-label>
      <div>
        <h2>+Add Image</h2>
      </div>
    </ngx-dropzone-label>
    <ngx-dropzone-image-preview class="ngx-dropzone-image-preview" ngProjectAs="ngx-dropzone-preview"
      *ngFor="let f of files" [file]="f" [removable]="true" (removed)="onRemove(f)">
      <ngx-dropzone-label>{{ f.name }} ({{ f.type }})</ngx-dropzone-label>
    </ngx-dropzone-image-preview>
  </div>
</div>

Step 5: Add the following code to your app.component.scss file.

.main-container {
    display: flex;
    justify-content: center;
    margin-top: 100px;

    .custom-dropzone {
        height: 250px;
        width: 250px;
        background: #c5bdbd;
        color: #fff;
        border: 5px dashed white;
        border-radius: 5px;
        font-size: 20px;

        ::ng-deep .ngx-dropzone-image-preview {
            margin: 0 !important;
            height: 100% !important;
            width: 100%;

            img {
                width: 100%;
                height: 100%;
            }
        }
    }
}

Finally, save all codes and check the output 🙂 !

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories