是否可以禁用对cdkDrag子元素的拖动?

时间:2020-05-29 09:47:06

标签: angular angular-material angular-cdk

我正在使用Angular Material中的Angular CDK拖放(请参见文档here)。我想知道是否有可能禁用在cdkDrag 子元素上的拖动。问题是无法使用鼠标选择在input的可拖动元素中写的内容。

因此,我想做的是禁用对具有input指令的元素下的所有cdkDrag的拖动。

我尝试使用:

  • cdkDragHandle :这会将拖动拖到特定元素上,而不是我在此处想要执行的操作
  • cdkDragDisabled :这将禁止拖动整个元素,而不是我在此处要执行的操作

这是我的代码:

<div cdkDropList (cdkDropListDropped)="drop($event)">
    <div *ngFor="let element of array" cdkDrag>
        <div>
            <mat-form-field>
                <mat-label>Input 1</mat-label>
                <input matInput type="text">
            </mat-form-field>
            <mat-form-field>
                <mat-label>Input 2</mat-label>
                <input matInput type="number">
            </mat-form-field>
        </div>
    </div>
</div>

提前感谢您的帮助和时间。

2 个答案:

答案 0 :(得分:5)

您可以在表单字段上停止 mousedown 事件传播。将以下内容添加到表单字段元素:(mousedown)="$event.stopPropagation()"。

这会阻止在您尝试单击表单域时发生拖动事件,并让您与该表单域正常交互。

<div cdkDropList (cdkDropListDropped)="drop($event)">
    <div *ngFor="let element of array" cdkDrag>
        <div>
            <mat-form-field>
                <mat-label>Input 1</mat-label>
                <input matInput type="text"(mousedown)="$event.stopPropagation()">
            </mat-form-field>
            <mat-form-field>
                <mat-label>Input 2</mat-label>
                <input matInput type="number"(mousedown)="$event.stopPropagation()">
            </mat-form-field>
        </div>
    </div>
</div>

答案 1 :(得分:0)

这是一个简单的解决方法:

app.component.css

.display-none {
  display: none;
}

app.component.html

<div cdkDropList (cdkDropListDropped)="drop($event)">
    <div *ngFor="let element of array" cdkDrag>
        <div>
            <mat-form-field>
                <mat-label>Input 1</mat-label>
                <input matInput type="text" cdkDrag cdkDragPreviewClass="display-none">
            </mat-form-field>
            <mat-form-field>
                <mat-label>Input 2</mat-label>
                <input matInput type="number" cdkDrag cdkDragPreviewClass="display-none">
            </mat-form-field>
        </div>
    </div>
</div>

只需将cdkDrag cdkDragPreviewClass="display-none"添加到您的输入元素中即可。那应该对你有帮助。