The cdkDropList in Angular's drag and drop feature does not support the application of element styles

Just wanted to share my experience in case it helps someone else out there!

I've been working on an Angular project where I needed to create a Trello-like application. To enable dragging elements from one list to another, I installed the Angular cdk module and followed their guide.

https://i.sstatic.net/FF0S8.png

IMPORTANT: My application consists of multiple pages/components, and the page where I'm implementing the Trello interface is called BoardPageComponent.

Initially, I added the cdkDrag directive to make the element draggable, which was a good start.

However, when I added the cdkDropList directive to the parent element, the style of the children elements no longer worked properly while being dragged!

Resolution

During drag-and-drop operations within a cdkDropList, the DragAndDropModule creates a clone of the element at the document's body level. This can cause styling issues if your component is encapsulated.

Solution 1: An easy fix would be to move the styles of the draggable element to the global stylesheet.

Solution 2: Alternatively, you could disable encapsulation for that component using ViewEncapsulation.None:

@Component({
  selector: 'app-board-page',
  templateUrl: './board-page.component.html',
  styleUrls: ['./board-page.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class BoardPageComponent implements OnInit, OnDestroy {
  ....
}

While this solution works, remember that it might expose some styles to other components in your application. Make sure to handle component styling carefully.

Is there perhaps another approach we're missing?

Answer №1

Encountering a similar issue, I found that the dragged element lost its styling. There might be an alternative approach worth exploring.

While sticking to the default ViewEncapsulation.Emulated, my resolution involved ensuring that my component's CSS was not excessively scoped (e.g. overly specific selectors from draggable parent elements). This helped resolve the issue.

The use of .cdk-drag-preview proved to be beneficial in my case.

Answer №2

To customize the CSS for a specific element in your Angular component, you can use the "::ng-deep" pseudo-class within the host selector.

:host ::ng-deep h2 {
    color: red;
 }

Answer №3

Insight into this response

In summary: The issue stemmed from nested selectors in my SCSS code, which caused the styles to not be applied when an element was dragged because the drag action creates a copy of the element without its parent elements.

Here's how I resolved this styling issue effectively.

Understanding the situation


When the .cdk-drag-preview is generated, it replicates the element being dragged.

This replication occurs at the end of the HTML <body> element.

The crucial point here is that only the specific dragged element is duplicated, excluding its parent elements.

Identifying the problem


In my scenario, the crux was the nested structure of my SCSS selector, expecting the dragged element to have a parent class present during dragging, which wasn't the case.

For instance:

.example-parent-class {
  // Parent element styles
  .example-dragged-class { 
    // Styles for the draggable item
  }
}

However, upon dragging, the generated HTML displayed only:

<body>
  <div cdkdrag class="example-dragged-class cdk-drag cdk-drag-preview"></div>
</body>

With no sign of the parent element or its class, causing the styles to malfunction.

Locating the information


To investigate, while dragging with the Inspector tool active (F12 in Chrome), right-click and navigate to the </body> selector in the Elements tab. This allows inspection of the dynamically generated HTML structure of the dragged element.

Finding the solution


The resolution involved undoing the nesting and having the dragged element's class as a standalone in the component's SCSS for accurate utilization by .cdk-drag-preview.

For example:

.example-parent-class {
  // Parent element styles
}

.example-dragged-class {
  // Styles for the item to be dragged
}

Consequently, the original element's styles were successfully replicated without any additional configuration needed.

Consider adding styles for the placeholder if required.

Example:

.cdk-drag-placeholder {
  opacity: 0;
}

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 execution of the function halts as soon as the player emerges victorious

In my attempt to create a basic game where players compete to click their designated button faster to reach 100%, I am in need of assistance with implementing a logic that determines the winner once one player reaches or exceeds 100. Essentially, I want ...

How can I add a drop-down list to a cell within a table?

Can a drop-down list be added into a table cell? Thank you! Here is an excerpt of the code: $sql_query="SELECT nameOfwarning FROM warnings"; $sodss=mysqli_query($d,$sql_query); if (mysqli_num_rows($result)<1) ?> <select name = "warnings"> ...

Counting checkboxes in jQuery version 1.9

I recently upgraded my website from jQuery 1.6 to jQuery 1.9.1, and now some of my old code is not working as expected. Specifically, I have a piece of code that handles checkboxes in table rows, allowing only up to 5 checkboxes to be active at once and di ...

Issue-free AJAX call to Neo4j database on local server with no 'Access-Control-Allow-Origin' problem

I'm currently working on a basic JavaScript AJAX request to connect from a MAMP server running at localhost:8888 to a Neo4j database running on localhost:7474. The issue I'm encountering is the following error message: XMLHttpRequest cannot l ...

How can you effectively declare a computed getter in MobX that aggregates an observable list?

Within my project, I have a class hierarchy consisting of projects, task lists, and tasks. Each array is marked as @observable. Now, I am looking to create a "@computed get allTasks" function within the project class that aggregates all tasks from all task ...

Can a CSS class be added to a form_row in Symfony 4 Twig?

Need help with adding a CSS class to the entire form_row in a Symfony 4 twig template! Currently, my code only adds the class to the input tag, but I require it to be added to the parent div container. Here is the current code snippet: {{ form_ ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...

Storing blank information into a Mongodb database with Node.js and HTML

Can someone please assist me with solving this problem? const express=require("express"); const app=express(); const bodyparser=require("body-parser"); const cors=require("cors"); const mongoose=require("mongoose"); ...

Angular 5 is rendering a div even if there is no content present

I am currently using Angular 5.2 Firestore When using *ngIf isContent else noContent, my goal is to only render an Observable if it contains data. However, I am facing an issue where the logic always renders isContent even when there is no data present. ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...

Experiencing a snag with Angular2 and angular2-jwt: encountering an issue with AuthHttp where the JWT must consist

Encountering an issue with AuthHttp despite receiving a valid token from the authentication. The token has been confirmed as valid on . Currently working with Angular 4. Here is my code: Sign-In Code signIn(login: string, password: string) { this.U ...

What is the best way to switch between different styles for each paragraph using CSS?

I attempted to use the :nth-of-type selector, but I am uncertain if it is feasible or if it accomplishes what I desire. My goal is to create an alternating style: two paragraphs aligned on the left, followed by two on the right, and so forth, regardless of ...

Implementing SweetAlert2 in Vue.js to create a modal prompt for confirmation prior to deleting an item

I'm encountering an issue with sweetalert2 while using Laravel Vue for my app development. My goal is to have a confirmation modal pop-up when deleting a row from the database. However, whenever I click "Yes", the item is successfully removed. But if ...

Exploring the inner workings of AngularJS SEO in HTML5 mode: Seeking a deeper understanding of this hidden functionality

There are plenty of resources available for incorporating SEO-friendly AngularJS applications, but despite going through them multiple times, I still have some confusion, especially regarding the difference between hashbang and HTML5 mode: In hashbang (# ...

Learn how to display HTML content in trNgGrid using the $sce.trustAsHtml method

I am currently working with a table that has search options implemented using trNgGrid.js. The data for this table comes from a Sharepoint list where one of the columns contains HTML content that I need to display. To achieve this, I attempted using $sce. ...

Tips for including shared information across different ionic tabs

Is there a way to include some shared content, like a canvas, in between the content of different tabs in Ionic? I want this common content to be displayed across all tabs, while each tab still shows its own dynamic data below it. I attempted to add the c ...

Guide for displaying retrieved information on a Bootstrap Modal window following data submission in Yii2

I'm encountering an issue with a Modal popup that contains two fields. The first field is used to submit information and perform an internal database query, while the second field should display the returned data. Oddly enough, when testing the functi ...

Managing errors that occur while handling JSON with AJAX by implementing a suitable backup plan

Imagine there is a user.json file stored on a web server that contains: { "name” : “ivana”, “age” : “27” } Now, I make a request to retrieve this JSON data using the following code: var user = $.ajax({ url: pathsample.com/user.js ...

Positioning the close button on the top right edge of a Material-UI Dialog: A step-by-step guide

https://i.sstatic.net/ARTtq.png How can I include a close icon in the top right corner of the header section? I'm using the Material UI Dialog and everything works well, but I need a close button in the top section. Can anyone assist me with this? ...

The color of the button in HTML5 will remain constant and not shift

I have several buttons that function like radio buttons - only one can be selected at a time: <button id="btn-bronze" name="btn-bronze" type="button" class="blue-selected">Bronze</button> <button id="btn-silver" name="btn-silver" type="butt ...