angular – 在添加新项目时保持列表中的滚动位置
发布时间:2020-12-17 08:45:59 所属栏目:安全 来源:网络整理
导读:我有一个项目列表,我使用* 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.i
我有一个项目列表,我使用* 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,用于突出显示选择的项目. 当我更新列表时,可以在所选项目(大部分)上方和所选项目下方添加新项目.当发生这种情况时,所选项目将远离当前视图位置. 更新: 要做到这一点,我正在拯救 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元素会有延迟. 如何获得添加新元素的事件?
我觉得这样的事情对你有用:
模板 <div id="container" #cont>... 零件 @ViewChild('cont') contEl: any; thisIsCalledWhenNewItemISAdded() { let current = this.contEl.scrollTop; // ...Item added this.contEl.scrollTop = current; } 因此,您使用@ViewChild装饰器来获取组件中的元素.然后在添加新项目之前捕获scrollTop,并在添加项目后将其设置回来. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |