【问题标题】:*cdkDragPreview positioning Angular Material*cdkDragPreview 定位角材质
【发布时间】:2019-01-23 10:09:38
【问题描述】:

在拖动项目时使用*cdkDragPreview可以改变位置吗?现在我在拖动时所做的样式总是出现在光标的右下角。我想把它放在左上角。

有什么帮助吗?

【问题讨论】:

    标签: angular angular-material angular-cdk


    【解决方案1】:

    是的,您可以订阅 cdkDragMoved 并抵消您的 *cdkDragPreview

    示例

    以下示例将在 x 和 y 轴上偏移 100px 的预览

    <div cdkDrag
        [id]="storageNode.barcode"
        [cdkDragData]="storageNode"
        [cdkDragDisabled]="dragDisabled"
        (cdkDragMoved)="onDragMove($event)">
        <div title="Drag this entity and its children"
            class="entity-drag-handle"
            cdkDragHandle>
    
            {{storageNode.barcode}}
            <mat-icon *ngIf="!dragDisabled">
            drag_indicator
            </mat-icon>
        </div>
        <div
          [id]="storageNode.barcode + 'preview'"
          [ngStyle]="{'background-color': this.getBackgroundColor(0.6)}"
          class="entity-drag-preview"
          *cdkDragPreview>
             <h4>{{storageNode.barcode}}</h4>
             <p>{{formattedDescription}}</p>
        </div>
    </div>
    

    请记住,这使用了 typescript 3.7 的功能,这些功能在旧版本上不起作用

    public onDragMove(event: CdkDragMove<StorageEntity>): void {
        const nodeMovePreview = new ElementRef<HTMLElement>(document.getElementById(this.storageNode.barcode + 'preview'));
        const xPos = event.pointerPosition.x - 100;
        const yPos = event.pointerPosition.y - 100;
        if (nodeMovePreview?.nativeElement) {
            nodeMovePreview.nativeElement.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
        }
    }
    

    【讨论】:

    • 谢谢!对于尚未使用 TypeScript 3.7 的用户,您可以替换一行以使其在 TypeScript 3.6 及以下版本中工作,将 if (nodeMovePreview?.nativeElement) { 更改为 if (nodeMovePreview &amp;&amp; nodeMovePreview.nativeElement) {
    【解决方案2】:

    [HTML]

    <div
        cdkDrag
        (cdkDragReleased)="cdkDragReleased($event, i)"
        (cdkDragDropped)="cdkDragDropped($event)">
    
     <div class="my-placeholder" *cdkDragPlaceholder></div>
    
     <div class="my-preview" *cdkDragPreview></div>
    
    </div>
    
    

    [CSS]

    .my-placeholder {
      background-color: #000;
    }
    .my-preview {
       transform: scale(0.7) translate(-200px, -100px);
    }
    

    我在 .my-preview 中使用 translate 将项目放置在 x 轴和 y 轴上,然后使用比例缩小以使其看起来更小

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 2019-06-14
      • 2019-04-05
      • 2018-05-08
      相关资源
      最近更新 更多