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

The orientation of the displayed images has turned vertical, breaking away from the traditional horizontal

My problem lies in trying to horizontally display the images fetched from the database. I attempted using "inline-block" but it proved ineffective. Despite looking for alternative solutions, none seemed to be a fit for my situation. $db = mysqli_connect(" ...

Is using display:table an effective approach for achieving equal height columns?

I am currently working on a responsive design project and I need two columns of equal height. I do not want to rely on JavaScript for this, and I prefer having some whitespace between the columns to enhance readability. I have tried two different layouts; ...

Displaying incorrect symbols with icon fonts

I have successfully integrated icon fonts into my simple web page. Check it out on jsFiddle here My design is similar to this example, but instead of bars, I see a snake icon displayed. How can I fix this issue with the fonts? Here is the code snippet: ...

Move the creation of the HTML string to an HTML template file within ngx bootstrap popover

I have incorporated ngx bootstrap in my project through this link To display dynamic HTML content in the popover body, I am using a combination of ngx-bootstrap directives and Angular template syntax as shown below: <span *ngFor="let item of items;"&g ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...

Choosing Between EMs and Pixels for Font Sizes: A 2011 Perspective

In the past, EMs were favored over pixels for font size because they could scale with IE6 while pixels could not. Nowadays, modern browsers can handle pixel-sized font scaling correctly. Another advantage of EMs is that they cascade, unlike pixels. But if ...

Issue with displaying data using a custom pure pipe and boolean in ngIf condition

For my current web project, I require a friendship/follow feature. There are two roles involved: admins and regular users. Regular users have the ability to follow other users, while admins do not possess this capability. When a user wishes to follow anot ...

Tips for synchronizing response JSON with TypeScript interface in Angular 6

I am retrieving a list of files that have been uploaded from a backend endpoint, and it comes back in this format: [ { "filename": "setup.cfg", "id": 1, "path": C:\\back-end\\uploads\\setup.cfg", ...

Customize the background color of Material UI input components on standard labels

Currently using react material ui and interested in changing the background color of a standard input. The issue arises when the label is overridden by the background color when the input is not selected. Input selected Input not selected This is my att ...

Describe a Typescript Interface Value as a collection of strings or any input provided as an argument

Uncertain if the question title is accurate - currently developing react components within a library that has specific predefined values for certain properties. However, additional values may need to be added on a per usage basis. So far, this setup is fun ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

Tips for saving the visibility status of a <div> in your browser bookmarks?

Currently, I am in the process of developing a single webpage (index.html). The navigation bar at the top includes links to hash references (DIV IDs). If JavaScript is enabled, clicking on these links triggers a JavaScript function with the onclick attribu ...

Designing functional components in React with personalized properties utilizing TypeScript and Material-UI

Looking for help on composing MyCustomButton with Button in Material-ui import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps { 'aria-label': string, // Adding aria-label as a required pro ...

Alter the website link in an HTML file as well as in the corresponding CSS and JavaScript

Is it possible for JQuery to alter URLs within a CSS or Javascript resource before they are loaded into the browser, or even as they load in the browser? URLs typically point to resources such as images and fonts. I have been considering this idea becaus ...

Tips for customizing ngTable with expandable detail panels

I am currently working on styling a layout using ng-table, which includes a table within each row. The expanding functionality in Angular is implemented as follows: <tr ng-if="org.expanded" ng-repeat-end> <td></td> <td></td& ...

Is it detrimental to my search engine ranking if I utilize CSS display:none?

Imagine having valuable content that is initially hidden with CSS, and then using javascript to reveal it only when the user clicks on certain links. Even users without javascript enabled can access this content by following the links to a new page where i ...

Tips for creating a personalized asynchronous Express handler that seamlessly receives specific typed parameters

In my quest to create a unique Express endpoint wrapper, I aim to wrap async functions and handle errors effectively. The current implementation is basic but functional: import type {Request, RequestHandler, Response} from 'express'; type Handle ...

Why won't my picture track the movement of the cursor?

I am trying to make my image follow the cursor using a specific code, but it doesn't seem to be working. I'm having trouble figuring out what's wrong with it. Here is the code snippet that I'm currently using: function followIt(e) ...

The Yii2 CORS filter is throwing an error indicating the absence of the 'Access-Control-Allow-Origin' header

After reading through the information provided in this particular question, I have configured my rest controller behavior as follows: public function behaviors() { $behaviors = parent::behaviors(); $auth= $behaviors['authenticator'] = [ ...