angular 掉落事件不一致

angular drop event is inconsistent

Minimal reproduction: https://stackblitz.com/edit/buggydrop

我正在制作一个简单的网站,用户将一个元素拖放到另一个元素上,以便每个元素的内容相互交换。

但是,问题出在 (drop)="BuggyonDrop($event)"$event 给拖动的元素 DragEvent

换句话说,如果我将 <p id="unique0"> 拖放到 <p id="unique2"> 上,drop() 上的事件信息是 <p id="unique0">...

奇怪的是,当我执行 console.log(event.target.id) 时,结果是 unique2

此外,如果我将调试器放在 console.log 的正下方,结果就很好(按预期工作)。

所以这真的很奇怪和不一致。

我不得不花费数小时来查找原因和解决方法。原来不使用 *ngFor 是一个解决方案(必须手动一个一个地放置数据绑定值)。

我已经在 chrome 和歌剧上测试过...

here is the console.log result when I do the following code

console.log("BuggyonDrop")
console.log(event)
console.log(event.target)
console.log(event.target.id)

如您所见,event.target 给出了 unique3 元素,但是当我这样做时 event.target.id 它给了我 unique0

不太确定为什么会这样

默认情况下,ngFor 循环按值跟踪项目。在您的代码中,您交换了 drag/drop 操作中涉及的两个项目的值。循环可能会交换循环中的项目索引以在相同位置保持相同的值。

为确保 ngFor 循环索引引用正确的目标元素,您应该 track 索引项:

*ngFor="let id of good.idArray; index as i; trackBy: trackByIndex"

其中 trackByIndex 是组件的方法 class:

public trackByIndex(index, item) {
  return index;
}

请参阅您的 stackblitz 的 this modified version 以获取演示。您会注意到我重命名了一些属性以反映拖放不再有问题的事实...