使用 primeng p 树组件停止节点丢弃事件



我正在使用primeng p树组件,我想禁止将某些节点类型放入另一个节点类型中。

例如,我有类型文件夹的节点和另一个文件类型的节点,我只希望文件类型的节点移动到文件夹类型的节点内。我想禁止在另一个文件夹节点内移动文件夹节点。 (和其他规则

<p-tree [value]="filesTree7" draggableNodes="true" droppableNodes="true" dragdropScope="files" selectionMode="single" [(selection)]="selectedFile2" [contextMenu]="cm" (contextmenu)="onContextMenu($event)"
(onNodeDrop)="onNodeDrop($event)"></p-tree> 

我试图像这样停止液滴的传播:

onNodeDrop(event) {
console.log("onNodeDrop");
event.originalEvent.stopPropagation();
event.originalEvent.preventDefault();
return;
}

但它不起作用。

当我在这里查看 primeng 代码时:primeng 树组件代码源似乎onNodeDrop事件发出得太晚了。

您有任何想法吗?

在实现此功能之前,解决方法可能是重写Tree组件的allowDrop方法并编写自己的删除逻辑实现。 但是,您可能(实际上应该(想要使用原始方法中涵盖的删除逻辑并添加您的位。

现在prototyping可能看起来像这样:

  • 在使用pTree的组件中,通过ViewChild获取Tree

    @ViewChild(Tree) tree: Tree;
    
  • 然后在constructor,或ngOnInit或任何适合您的情况,prototypeallowDrop

    Tree.prototype.allowDrop = (dragNode: any, dropNode: any, dragNodeScope: any): boolean => {
    return this._overrideAllowDrop(dragNode, dropNode, dragNodeScope)
    }
    

_overrideAllowDrop用于简洁目的。要取消下降,只需return false.

此外,您可以利用树实例dragDropService来显示错误消息,以防删除失败。

例如:

this.tree.dragDropService.dragStop$.subscribe((data) => {
if(this.failed){ // set failed to true in your custom drop logic
alert('Error!')
}
})

但是此解决方法的缺点是删除逻辑应该在 UI 端,如果您的逻辑需要后端干扰,则此解决方法可能没有太大帮助。

虽然后端涉及我的情况,但逻辑很简单,所以我把它移到了 UI 端,因此prototyping达到了目的。

如果你希望单个节点不可拖放或可拖动,则必须在数组中设置可拖动/可拖放的参数:

{
"label": "Note e Commenti",
"icon": "fa-file-word-o",
"draggable":false,
"droppable":false,
"data": {
"id": 1,
"nome": "Note e Commenti",
"testo": "Note e Commenti",
"idCategoria": 2,
"idTipologia": 1
}
},

这有一些重要的其他细节,尤其是 bind(( 函数

export class myClass implements AfterViewInit {
@ViewChild('primeTree') primeTree: Tree;  // named in HTML

ngAfterViewInit() {
// get the original function AND bind it to the tree - important!
const originalAllowDrop = this.primeTree.allowDrop.bind(this.primeTree);

// replace the allowDrop function with this
this.primeTree.allowDrop = (dragNode: TreeNode, dropNode: TreeNode, dragNodeScope: any): boolean => {
// let the original function do the pre-check, and then check for special cases
return originalAllowDrop(dragNode, dropNode, dragNodeScope) && this.allowDrop(dragNode, dropNode, dragNodeScope);
}
}
private allowDrop(dragNode: TreeNode, dropNode: TreeNode, dragNodeScope: any): boolean {
// your logic here
if (imNotHappy) {
return false
}
return true;
}
}

最新更新