Drag and Drop File Upload with Angular 2

I'm currently working on incorporating a drag and drop upload feature for angular 2, similar to the one found at:

Given that I am using angular 2, my preference is to utilize typescript as opposed to jquery. After some research, I came across a library called ng2-file-upload and attempted to integrate the drag and drop functionality. However, I have encountered difficulties in making it function properly. Here is what I have so far:

Modified Upload.component.ts File:

Component({
  selector: 'upload',  
  templateUrl: 'app/components/upload/upload.component.html',
  styleUrls: ['app/components/upload/upload.component.css'],
providers: [ UploadService ]
})
export class UploadComponent {

public uploader:FileUploader = new FileUploader({url: URL});
    public hasBaseDropZoneOver:boolean = false;
    public hasAnotherDropZoneOver:boolean = false;

    public fileOverBase(e:any):void {
        this.hasBaseDropZoneOver = e;
    }

    public fileOverAnother(e:any):void {
        this.hasAnotherDropZoneOver = e;
    }
}

Adjusted upload.component.html Content:

<section id="dropzone">
    <div class="panel panel-default">

        <div class="panel-body">

            <!-- Standard Form -->
            <h4>Select files from your computer</h4>
            <br>
            <form  enctype="multipart/form-data" id="js-upload-form">
                <div class="form-inline">
                    <div class="form-group">
                        <input type="file" name="files[]" multiple (change)="fileChangeEvent($event)">
                    </div>
                    <button type="submit" class="btn btn-sm btn-primary"  (click)="upload()">Upload files</button>
                </div>
            </form>
</div>
    </div>



            <!-- Drop Zone -->
            <h4>Or drag and drop files below</h4>
        <br>
            <div ng2FileDrop
             [ngClass]="{'another-file-over-class': hasBaseDropZoneOver}"
             (fileOver)="fileOverBase($event)"
             class="well upload-drop-zone">
            Drop Files Here
        </div>
    </section>

Adjusted upload.component.css Styling:

.upload-drop-zone {
    color: #ccc;
    border-style: dashed;
    border-color: #ccc;
    line-height: 200px;
    text-align: center
}
.another-file-over-class {
    border: dashed 3px green;
}

Answer №1

It appears that you forgot to include the uploader binding in your html code.

<div ng2FileDrop
     [ngClass]="{'additional-file-over-class': hasBaseDropZoneOver}"
     (fileOver)="fileOverBase($event)"
     [uploader]="uploader"
     class="container upload-drop-zone">
     Drop Your Files Here
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instead of relying on Vue TypeScript, we are leveraging IntelliJ with TypeScript 5.0.3 to compile our Vue project

My current version of IntelliJ IDEA is 2023.1 (Ultimate Edition) Build #IU-231.8109.175, released on March 28, 2023. I am facing an issue where my project fails to compile using "Vue TypeScript", resulting in some type mismatches being overlooked. In the ...

Once the Angular project has been initialized, the Button disable attribute cannot be modified

In my Ionic-Angular project, I am creating registration pages where users input their information in multiple steps. For each step, there is a button that remains disabled until the correct information is entered. An issue arises when transitioning to the ...

NextJS is facing a dilemma as it struggles to understand why a simple prop passing to display a p tag is not rendering anything. Could the issue lie in data fetching and display

Working in NextJS, I set up an api endpoint, debugged client state issues, and ensured my state variables were correct. However, I am still unable to render the expected output. I am attempting to display a JSON object like this: [{"id":"cl ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...

What could be the reason for `process.env.myvariable` not functioning in a Next.js project with TypeScript

After creating a file called .env.local in the root directory of my project, I added a variable called WEBSOCKET_VARIABLE=THIS_IS_TEXT to it. However, when I try to access it using process.env.WEBSOCKET_VARIABLE, nothing is found. What could be causing ...

Unable to modify the date input format in Angular when utilizing the input type date

I am currently working with angular 10 and bootstrap 4. I am trying to update the date format in an input field from (dd/mm/yyyy) to DD/MM/YYYY, but I am facing issues. Below is my angular code: <input type="date" id="controlKey" cl ...

What's the Advantage of Using a Getter for a Public Field in Angular?

Having come from a background in Java where the practice is to make variables as private as possible, I've noticed in Angular that private fields are not used frequently. What is the reasoning behind not making fields private if it's possible? ...

Screen a roster for shared elements with another roster

Within my dataset, I am working with a List of Objects that adhere to the following Model structure: export class Animal{ public aniId: number; public aniName: string; } export Class Zoo{ public id: number; public name:string; public aniId: number ...

Issue encountered while setting up Ngb Module (Bootstrap) in Angular

Looking to add Ngb to an Angular project. Running Node.js version v19.1.0 and have attempted --force and --legacy-pear-drops. Also tried reinstalling Node.js. Error log: `npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While r ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

Get rid of the box-shadow that appears on the top side of mat-elevation

I placed a mat-paginator at the bottom of my mat-table which is styled with a mat-elevation-z4 class. However, when I added the mat-elevation-z4 class to the mat-paginator component as well, the upper shadow from the paginator appears to overflow onto the ...

How can I provide type annotations for search parameters in Next.js 13?

Within my Next.js 13 project, I've implemented a login form structure as outlined below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { signIn } from "n ...

Arrange the elements within the anchor tag in a vertical line using Angular Material

Is there a way to style the elements within an anchor tag in Angular Material so that they display in a single line? I am looking for the CSS solution to achieve this outcome. This is my current HTML code: <a mat-list-item [routerLink]="['das ...

Youngster listens for guardian's occurrence in Angular 2

While the Angular documentation covers how to listen for child events from parents, my situation is actually the opposite. In my application, I have an 'admin.component' that serves as the layout view for the admin page, including elements such a ...

Using Angular 6 to Share Data Among Components through Services

I am facing an issue in my home component, which is a child of the Dashboard component. The object connectedUser injected in layoutService appears to be undefined in the home component (home userID & home connectedUser in home component logs); Is there ...

Tips on ensuring JSON object structure with type and interface in an Angular application

In my angular project, I have created a router config file to handle routing efficiently. This config file contains JSON data like this: router.config.ts { branch:{ list:'/app/branch/list', add:'/app/branch/add' }, ...

Creating a TypeScript declaration file for a singular module

Consider the following directory structure: src/ ├── foo.ts ├── bar.ts ├── baz.ts ├── index.ts If foo.ts, bar.ts, and baz.ts each export a default class or object, for example in foo.ts: export default class Foo { x = 2; } I ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...

Conditional type in Typescript can be used to infer tuple types

Why are output1 and output2 not both inferred as [number, number, number] in the following code snippets? Snippet 1 : type InferTuple1<T> = T extends any[] ? [...T]: never; const func1 = <T>(t: InferTuple1<T>) => t; const output1 = ...

Using Jest in Typescript to simulate fetch responses

I am currently facing an issue with mocking the global fetch function using Jest and dealing with the Response type. Specifically, I only require the response.ok and response.json properties, but I am struggling to set the return data of fetch without spec ...