拖放式角垫树

时间:2019-09-10 11:41:43

标签: angular angular-material2 angular-dragdrop angular-tree-component

我正在将 angular material flat tree 用于 drag and drop

我使用stackblitz link中的示例实现了 drag and drop

将父节点拖放到子节点时出现错误。

  

这是错误无法读取未定义的属性'findIndex'

Instead of showing that error i want to disable the action of DND of parent to child.

这是我到目前为止的 work 。 预先感谢。

1 个答案:

答案 0 :(得分:0)

我刚刚复制并粘贴了您提供的示例的drop()代码,它可以正常工作。 不确定是否了解问题的出处,但仍然可以尝试删除函数并添加它:

// recursive find function to find siblings of node
findNodeSiblings(arr: Array<any>, id: string): Array<any> {
  let result, subResult;
  arr.forEach(item => {
    if (item.id === id) {
      result = arr;
    } else if (item.children) {
      subResult = this.findNodeSiblings(item.children, id);
      if (subResult) result = subResult;
    }
  });
  return result;
}

  drop(event: CdkDragDrop<string[]>) {
    if (!event.isPointerOverContainer) return;
    const visibleNodes = this.visibleNodes();
    const changedData = JSON.parse(JSON.stringify(this.dataSource.data));
    const node = event.item.data;
    const siblings = this.findNodeSiblings(changedData, node.id);
    const siblingIndex = siblings.findIndex(n => n.id === node.id);
    const nodeToInsert: PARENTNODE|CHILDNODE = siblings.splice(siblingIndex, 1)[0];
    const nodeAtDest = visibleNodes[event.currentIndex];
    if (nodeAtDest.id === nodeToInsert.id) return;
    let relativeIndex = event.currentIndex; // default if no parent
    const nodeAtDestFlatNode = this.treeControl.dataNodes.find(n => nodeAtDest.id === n.id);
    const parent = this.getParentNode(nodeAtDestFlatNode);
    if (parent) {
      const parentIndex = visibleNodes.findIndex(n => n.id === parent.id) + 1;
      relativeIndex = event.currentIndex - parentIndex;
    }
    const newSiblings = this.findNodeSiblings(changedData, nodeAtDest.id);
    if (!newSiblings) return;
    newSiblings.splice(relativeIndex, 0, nodeToInsert);
    this.rebuildTreeForData(changedData);
  }

这并不能真正回答您最初问题的出处,但我仍然建议您充分理解这段代码,因为它看起来可以正常工作。如果要添加更多选项,请从头开始。

相关问题