Using the example from CDK drag and drop, I want to add a preview of the dragged element with left and top positions without the transform style.
HTML
<div class="example-boundary">
<div class="example-box" cdkDragBoundary=".example-boundary" cdkDrag>
I can only be dragged within the dotted container
</div>
</div>
<button> Preview the dragged element </buttona>
TS
import {Component} from '@angular/core';
import {CdkDrag} from '@angular/cdk/drag-drop';
/**
* @title Drag&Drop boundary
*/
@Component({
selector: 'cdk-drag-drop-boundary-example',
templateUrl: 'cdk-drag-drop-boundary-example.html',
styleUrls: ['cdk-drag-drop-boundary-example.css'],
standalone: true,
imports: [CdkDrag],
})
export class CdkDragDropBoundaryExample {}
Current state
When you drag the element you have this div in DOM
<div _ngcontent-ng-c2320506461="" class="example-boundary">
<div _ngcontent-ng-c2320506461="" cdkdragboundary=".example-boundary" cdkdrag="" class="cdk-drag example-box" style="transform: translate3d(202px, -2px, 0px);">
I can only be dragged within the dotted container
</div>
</div>
Expected result.
When you drag the element and click the preview button it should open the preview element which looks like this.
<div class="example-boundary">
<div class="example-box" style="left: 96.13%; top: 9.92%; display: block;">
Now I can't be dragged, sorry
</div>
</div>
Meaning the transform style should be replaced with left and top positions.
2
Answers
@angular/cdk/drag-drop
internally uses transform property for placing the box. Whethertop
,left
andposition
properties are used ortransform
is used in internal detail of the package and should be understood to be encapsulated. You can achieve the same results using both ways. If there is anything specific you want to do withtop
andleft
properties, you can either compute them fromtransform
and elements original position or code drag function in pure JS.TLDR; Try this working example which does what you ask, basically clones the Angular generated HTML and then unwanted attributes are removed manually
The main changes are the following:
TS:
isPreviewShown
which toggles which HTML is visible, either the preview or the originalshowPreview
which clones the draggable contents and then manually removes unwanted attributes (you’ll have to maintain this logic, so you may remove other attributes you don’t need)cssText
style attributes fromtranslate3d
totop/left
values. I used the following regular expression for ittransform:s*translate3d((.+?),(.+?),.+?)
and the replaced it toleft:$1; top:$2
HTML:
preview-container
which is where the preview is going to be shownmain-container
which is meant to make thepreview
to overlap the original contentCSS:
The little css added main need is to add
position: relative
to the main container so thepreview-container
size and position is shown relative to the main container.