2016-08-23 71 views
5

我有我使用*ngFor保持在列表滚动位置时,新项目会添加

<div id="container"> 
    <div 
     [class.selected]="selectedItem.id == item.id" 
     #container 
     *ngFor="let item of items; indexBy: byId">{{item.name}}</div> 
</div> 

我保持定期更新名单阵列显示项目的列表。

this.listService.index((items) => this.items = items) 

我有其用于突出显示选择的项目的selectedItem

当我更新列表时,可以将新项目添加到选定项目(主要)上方和选定项目下方。发生这种情况时,所选项目将从当前视图位置移开。 我想调整父div的scrollOffset是这样一种方式,列表中项目的位置保持在相同的视图位置。

更新:

要做到这一点,我现在的储蓄

this.offset; = this.container.scrollHeight - this.container.scrollTop; 

和更新this.items

this.listService.index((items) => { 
    this.items = items 
    this.container.scrollTop = this.container.scrollHeight - this.offset; 
}) 

这并不下班后添加了一行,但是,与超时工作包裹这究竟是我想要的。

setTimeout(() => { 
    this.scrollPosition.restore() 
}, 300) 

更新this.items后,是使新的DOM元素的延迟。

如何获得新元素添加的事件?

回答

3

我觉得这样的事情会为你工作:

模板

<div id="container" #cont>... 

组件

@ViewChild('cont') contEl: any; 

thisIsCalledWhenNewItemISAdded() { 
    let current = this.contEl.scrollTop; 

    // ...Item added 

    this.contEl.scrollTop = current; 
} 

所以你使用@ViewChild装饰获取该元素在你的组件。然后在添加新项目之前捕获scrollTop,并在添加项目后将其设置回来。

+0

无论如何,更新项目后scrollTop保持不变。我想更改scrollTop,以便在新项目添加到顶部时,视图中的项目不会被推下。更新我的问题。谢谢 –

相关问题