2016-08-23 130 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,以便在新項目添加到頂部時,視圖中的項目不會被推下。更新我的問題。謝謝 –

相關問題