Changing background color during drag and drop in Angular 2: A step-by-step guide

A drag and drop container has been created using Angular 2 typescript. The goal is to alter the background color of the drag & drop container while dragging a file into it.

Typescript:

@HostListener('dragover', ['$event']) public onDragOver(evt){
 evt.preventDefault();
 evt.stopPropagation();
}

@HostListener('dragleave', ['$event']) public onDragLeave(evt){
 evt.preventDefault();
 evt.stopPropagation();
}

@HostListener('drop', ['$event']) public onDrop(evt){
 evt.preventDefault();
 evt.stopPropagation();
 let files = evt.dataTransfer.files;
 let valid_files : Array<File> = [];
 let invalid_files : Array<File> = [];
 if(files.length > 0){
   forEach(files, (file: File) =>{
     let ext = file.name.split('.')[file.name.split('.').length - 1];
     if(this.allowed_extensions.lastIndexOf(ext) != -1){
       valid_files.push(file);
     }else{
       invalid_files.push(file);
     }
   });
   this.filesChangeEmiter.emit(valid_files);
   this.filesInvalidEmiter.emit(invalid_files);
 } 
}

HTML:

<div class="dropzone" (filesChangeEmiter)="onFilesChange($event)"
    (filesInvalidEmiter)="onFileInvalids($event)">
   <div class="centered">Drop your file here!</div>
</div>

Attempt was made using HostBinding to modify the background color, but it was unsuccessful. Is there a way to detect the dragging state and adjust its CSS?

Answer №1

To implement custom styling in your Angular component, you can make use of the [ngStyle] directive.

Start by declaring a variable in your component to hold the background color:

let backColor:string="transparent";

Assign a value to the variable during a drop event and apply it like this:

(1) Use inline CSS with [ngStyle] as shown below:

(2) Alternatively, return styles from a method in your component:

 private setStyles(): any {
    let styles = {
        'background-color': this.backColor
    };      
    return styles;
}

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

Obtain the angular version during the Azure build pipeline execution

Is there a way to retrieve the current version of Angular used in our project as we build it through the pipeline? We leverage Azure DevOps and utilize YML for configuring our pipelines. Although I have managed to extract the "key" for "angular/core" from ...

``There is an issue arising from the interaction between EventEmitter and Custom

Working with an Angular 8.3.14 project. We have implemented an EventEmitter to communicate a string value to the parent component. Child Component Setup @Output() pepe = new EventEmitter<any>(); ngOnInit() { this.pepe.emit('pepe'); } ...

Instructions on how to reset or restore to the initial spawn point

I am currently attempting to simulate a spawn process using the mock-spawn module. However, I am encountering issues with restoring the mock after running subsequent tests. I attempted to use mySpawn.resotre(), but it appears that this function does not e ...

Overlay text on top of image with fading transparency when hovering over it

Is there a way to make the transparent layer that appears when hovering over an image on a card only cover the image itself and not extend onto the footer of the card? Currently, the image on the card covers most of it, and I want the hover overlay to beh ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

The basic CSS container fails to properly align its elements as intended

Recently, I created a CSS div using Bootstrap and added some custom styling. You can check out the fiddle for a live demo of the code: https://jsfiddle.net/w9gyc0t5/. Here's the actual code: <!-- Bootstrap docs: https://getbootstrap.com/docs -- ...

Troubleshooting: Custom icons not displaying in Next.js application

Every time I attempt to use icons that I have loaded into my source code, I keep getting this default icon displayed: I'm uncertain about what exactly is causing this issue. Here is the layout of my file tree for reference: When attempting to utiliz ...

The NgIf directive is triggered, but the element remains hidden. It is unclear whether it briefly appears and then disappears, or if it never shows up at all

Having trouble with the element marked with ***. My goal is to create and fill the item-list with ion-items, but I encountered duplicate entries. To resolve this issue, I tried using a flag called hall.show. The console.log confirms that the show attribute ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

Utilizing Conditional Aurelia Validation Based on Element's Display Status

Currently, I am in the process of setting up a license subscription form using Aurelia and the Aurelia Validation plugin. Within this form, there is a fieldset dedicated to personal information which contains mostly required fields that are validated by Au ...

Mouse cursor does not display as a pointer when utilizing an SVG image on Internet Explorer

Consider this html: <a href="http://www.wikipedia.com"> <object data="http://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg" type="image/svg+xml"> <img src="http://herdeirodocaos.files.wordpress.com/2007/11/wikipedia-lo ...

Subscription Code Incrementally Triggering Upon Each Component Load

Within the initialization of my component, I have the following code: public Subscription: Subscription; ngOnInit() { this.subscription = this.myService.currentData.subscribe( dataReceived => { this.data = dataReceived; this.useDa ...

Unable to move cursor in contenteditable section

I am currently working on developing a rich text editor in React, but I have encountered an issue that has me stuck. The problem I am facing is that as I type each character, the insertion point does not update accordingly, causing the cursor to remain stu ...

Setting up an empty array as a field in Prisma initially will not function as intended

In my current project using React Typescript Next and prisma, I encountered an issue while trying to create a user with an initially empty array for the playlists field. Even though there were no errors shown, upon refreshing the database (mongodb), the pl ...

Utilize the RRule library in JavaScript by incorporating the rrule.min.js script

I am having trouble integrating the library https://github.com/jakubroztocil/rrule into my website. Whenever I try to do so, I encounter the error: Uncaught SyntaxError: Unexpected token { I have attempted the following: <!DOCTYPE html> <html ...

Blog Format Featuring Side-by-Side Columns

Is there a way to achieve horizontal columns that don't cut off articles and flow seamlessly into the next column? I want the columns to have varying heights, such as Post A at 60% height, followed by Post B at 40% height, then Post C at 30%, and fina ...

The Ng2AutoCompleteModule library, which contains the ng2-auto-complete module, was not correctly processed by ngcc or is not compatible with Angular Ivy

I am in the process of upgrading Angular from version 2 to 15 and encountering an error. Can anyone provide assistance with this issue? It seems that the ng2-auto-complete library, which declares Ng2AutoCompleteModule, has not been processed correctly by ...

Exploring the Benefits of Angular 2 Beta Typings within Visual Studio (ASP.NET 4)

During my initial experiences with Angular 2.0 alpha versions, I utilized the files from DefinitelyTyped to incorporate typings for TypeScript in Visual Studio. The process was straightforward - simply adding the d.ts files to the project. However, as we t ...

Creating a searchable and filterable singleSelect column in the MUI DataGrid: A step-by-step guide

After three days of working on this, I feel like I'm going in circles. My current task involves fetching data from two API sources (json files) using the useEffect hook and storing them in an array. This array contains a large number of products and a ...

Ways to prevent image toggling when the mouse moves out of it or when the hover effect stops

I'm looking to toggle between two images on mouseover/hover and stop the toggling when hovering stops. Here is the HTML code I have: <div class="fader"> <img src="image1" /> <img src="image2" /> </div> This is the JQuery ...