如何更改 z-index 的 Angular CDK 拖放?

How to change z-index of Angular CDK Drag and Drop?

我在我的应用程序中使用 Angular Material CDK Drag and Drop Functionality。拖放功能工作正常,除非我在对话框中使用它(对于大多数组件,我使用的是 Nebular,在本例中是 Nebular 对话框)。我遇到的问题是,只要我在对话框中拖动一个可拖动元素,该元素就会消失在对话框后面。放下它后,它会重新出现在正确的位置。在屏幕截图中,我将 "AAAA" 元素拖离列表 - 它消失在对话框后面。

Stackblitz:https://stackblitz.com/edit/angular-znqckb

我正在使用以下实现:

 <div cdkDropList cdkDropListOrientation="horizontal" class="example-list" [cdkDropListData]="techs"
     (cdkDropListDropped)="drop($event)">
     <button *ngFor="let tech of techs" nbButton cdkDrag>{{tech}}</button>
 </div>

Component.ts:

drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.techs, event.previousIndex, event.currentIndex);
}

我没有修改样式sheet。我认为这个问题可以通过修改 z-index 以某种方式解决,但我不知道如何将它应用到 "dragging" 元素。

我自己也在努力解决这个问题,目前我使用的是一种粗略的解决方法。在您的全局样式 (styles.scss) 中将 .cdk-overlay-container 的 z-index 强制设置为 1000 应该会得到您想要的结果。但这不是最佳做法。

在styles.scss中添加:

.cdk-overlay-container {
  z-index: 1000 !important;
}

Stackblitz here

据我所知,不可能在拖动预览("dragging" 元素)上强制使用 z-index,因为 cdk 将其 z-index 动态设置为内联样式。您使用的 Nebular 库似乎将覆盖容器的 z-index 设置为 1040。Angular Material 库将拖动预览的 z-index 设置为 1000,这就是它位于覆盖层后面的原因。 Vanilla Angular Material 将 cdk overlay 的 z-index 设置为 1000,因此拖放将在这种情况下起作用。

您可以更改 DragRefConfig 以在您的组件中注入正确的配置(具有所需的 z-index)。例如:

const DragConfig = {
  dragStartThreshold: 0,
  pointerDirectionChangeThreshold: 5,
  zIndex: 10000
};

providers: [{ provide: CDK_DRAG_CONFIG, useValue: DragConfig }]

预览元素的 z-index 将为 10000 ;-)

更多信息:https://material.angular.io/cdk/drag-drop/api#DragRefConfig

对于比 9 更早的 angular material 版本。

在 html 可拖动元素中:

<div ... cdkDrag (cdkDragStarted)="onDragStarted($event)"</div>  

在组件 ts:

export class ...{
  zIndexSerial: number = 1000;

  onDragStarted(event: CdkDragEnd): void {
    event.source.element.nativeElement.style.zIndex=this.zIndexSerial+"";
    this.zIndexSerial = this.zIndexSerial+1;
  }

任何遇到相同问题的人 issue.I 发现解决方案是 z-index 仅适用于定位元素 Refer to this link description here

对于 Angular 版本 8,我将以下内容添加到 styles.scss 并让它在模态中工作:

.cdk-drag-preview {
    z-index: 9000 !important;
}

参见 https://material.angular.io/cdk/drag-drop/overview#styling

中的 .cdk-drag-preview