Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element style doesn't apply when using cdkDropList (Angluar cdk drag and drop)

I am posting this question just to answer it myself in case anyone is struggling like I did!

I'm working on an angular project to implement a Trello-like application. I want to be able to drag an element from one list to another so I installed the Angular cdk module and followed their guide.

enter image description here

NOTICE: My application is broken into several pages/components, the page were I am implementing that interface (Trello) is called BoardPageComponent.

First I added the cdkDrag directive and the element became draggable which is a good start!

Then I added the cdkDropList directive to the parent element, the children elements were still draggable BUT their style no longer works while they are dragged !

Solution

When dragging an element inside of a cdkDropList the DragAndDropModule creates a clone of that element but at the body level of the document. So if your component is encapsulated then it's style won't apply !

Solution 1: One quick solution would be to just move the style of that draggable element and put it in the global style file.

Solution 2: Another solution would be to disable the encapsulation of that component with ViewEncaplusation.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 {
  ....
}

This will work but you should be aware that this may leak some style to other components of your application. So make sure to encapsulate the component's style manually.

Or maybe there is another way ??

like image 432
Yezan Rafed Avatar asked May 02 '20 13:05

Yezan Rafed


2 Answers

I had the same issue: the dragged element was unstyled. And yes, there may be another way.

While keeping the default ViewEncapsulation.Emulated, my solution was to ensure my component's CSS was not overly scoped (e.g. having draggable parent's selectors in the path for draggable may be too specific).

Using .cdk-drag-preview was helpful to me.

like image 130
Michael R Avatar answered Oct 17 '22 18:10

Michael R


In your scss file add specific css in host ng deep selector

:host ::ng-deep h2 {
    color: red;
 }
like image 35
Gourav Garg Avatar answered Oct 17 '22 18:10

Gourav Garg