gpt4 book ai didi

angular - 如何限制拖放容器仅接受 Angular Material Drag-Drop Feature 中的一项

转载 作者:行者123 更新时间:2023-12-04 13:00:14 29 4
gpt4 key购买 nike

当使用@angular/cdk/drag-drop 模块(Angular Material Drag and Drop)时......有没有办法限制放置容器以便只接受一个值而不是多个值?我正在尝试创建表单,用户可以将图像拖放到应该只有一个项目的字段中。我正在使用标准示例代码来实现 Drag and Drop | Angular Material但找不到可以限制放置项目数量的解决方案,第二个无法找到保持拖动列表相同的解决方案(拖动的项目将保留在拖动容器中),因此您复制而不是将项目移动到放置容器。是否有任何解决方案或可以帮助示例代码的人?

HTML:

    <div class="example-container">
<h2>To do</h2>

<div
cdkDropList
#todoList="cdkDropList"
[cdkDropListData]="todo"
[cdkDropListConnectedTo]="[doneList]"
class="example-list"
(cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let item of todo" cdkDrag>{{item}}</div>
</div>
</div>

<div class="example-container">
<h2>Done</h2>

<div
cdkDropList
#doneList="cdkDropList"
[cdkDropListData]="done"
[cdkDropListConnectedTo]="[todoList]"
class="example-list"
(cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let item of done" cdkDrag>{{item}}</div>
</div>
</div>

TS:
import {Component} from '@angular/core';
import {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';

/**
* @title Drag&Drop connected sorting
*/
@Component({
selector: 'cdk-drag-drop-connected-sorting-example',
templateUrl: 'cdk-drag-drop-connected-sorting-example.html',
styleUrls: ['cdk-drag-drop-connected-sorting-example.css'],
})
export class CdkDragDropConnectedSortingExample {
todo = [
'Get to work',
'Pick up groceries',
'Go home',
'Fall asleep'
];

done = [
'Get up',
'Brush teeth',
'Take a shower',
'Check e-mail',
'Walk dog'
];

drop(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex);
}
}
}

最佳答案

好的,这应该有效:

movementCount: number = 0;

drop(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else if(this.movementCount === 0){
this.movementCount++; // block next object from being moved
// copy obj being moved
var movingObj = event.previousContainer.data[event.previousIndex];

transferArrayItem(event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex);

// transfer complete so copy object back
event.previousContainer.data.push(movingObj);
}
}

我使用计数器来确定是否允许移动,但 bool 值也能正常工作(更好)。
您只需要添加额外的代码,这样当图像从它被带入的 div 中移除/删除时,计数器会返回到零/假,以便在需要时可以拖动另一个图像。

希望有帮助。

关于angular - 如何限制拖放容器仅接受 Angular Material Drag-Drop Feature 中的一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59061058/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com