1

我正在angular material flat tree使用drag and drop.

我使用来自 stackblitz linkdrag and drop的示例实现。

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

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

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

这是我迄今为止的工作。提前致谢。

4

1 回答 1

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);
  }

这并不能真正回答你原来的问题来自哪里,但我仍然建议你很好地理解这段代码,因为它看起来正在工作。如果您想添加更多选项,请在干净的基础上重新开始。

于 2019-10-09T13:11:48.203 回答