【问题标题】:Retain UI Element position when model updates using Angular cdkDrag使用 Angular cdkDrag 更新模型时保留 UI 元素位置
【发布时间】:2020-01-08 04:14:22
【问题描述】:

在一个视图中,我有一个组件使用 Angular cdkDrag 在仪表板上移动元素。

此组件的数据是从订阅 SignalR Hub 的父级(通过单向绑定)向下传递的。

我遇到的问题是在收到有效负载时,如果任何元素已被移动,它们会重置回默认 UI 布局(就像您刷新页面一样)。

有没有办法阻止这种情况?

我是否需要将新位置存储在缓存中,并在收到有效负载后应用之前的位置(来自缓存)?

下面是显示问题的 StackBlitz。该项目的结构与我的相似: https://stackblitz.com/edit/angular-cdk-drag-columns-ldd9n2

【问题讨论】:

    标签: angular drag-and-drop angular-cdk ngzone angular-renderer2


    【解决方案1】:

    所以我发现了这个问题,这似乎是 Ngfor “重建” DOM 的行为。

    详情请见:

    https://malcoded.com/posts/angular-ngfor/

    https://angular.io/guide/template-syntax#ngfor-with-trackby

    基本上是为了解决这个问题,我将它添加到 html 中:

    <div *ngFor="let item of items; trackBy: trackByItems">
      ({{item.id}}) {{item.name}}
    </div>
    

    这在 components.ts 中:

    trackByItems(index: number, item: Item): number { return item.id; }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      相关资源
      最近更新 更多