javascript - 将 ngFor 循环的最后一个元素滚动到视图中
问题描述
我的用户可以将条目添加到滚动列表的底部。但是,添加条目时滚动条不会自动向下移动,因此用户看不到他们新添加的条目。如何让我的滚动条始终处于向下滚动最多的位置以显示最新条目(使用 Angular 5)?
解决方案
您可以通过设置焦点将新条目滚动到视图中,如此 stackblitz所示。
- 如果 item 元素具有
tabindex
属性,则它们可以被聚焦 - 它们还应该具有样式属性
outline: none
(以删除焦点轮廓) - 应在项目元素上设置模板引用变量(例如
#commentDiv
) ViewChildren
对列表的更改由QueryList.changes
事件监控- 当检测到列表发生变化时,焦点设置在列表的最后一个元素上
HTML:
<textarea [(ngModel)]="newComment"></textarea>
<div>
<button (click)="addComment()">Add comment to list</button>
</div>
<div>
Comments
</div>
<div class="list-container">
<div tabindex="1" #commentDiv class="comment-item" *ngFor="let comment of comments">
{{ comment }}
</div>
</div>
CSS:
div.list-container {
height: 150px;
overflow: auto;
border: solid 1px black;
}
div.comment-item {
outline: none;
}
代码:
import { Component, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core';
...
export class AppComponent {
@ViewChildren("commentDiv") commentDivs: QueryList<ElementRef>;
comments = new Array<string>();
newComment: string = "Default comment content";
ngAfterViewInit() {
this.commentDivs.changes.subscribe(() => {
if (this.commentDivs && this.commentDivs.last) {
this.commentDivs.last.nativeElement.focus();
}
});
}
addComment() {
this.comments.push(this.newComment);
}
}
推荐阅读
- pytest - Pytest:在 pytest_addoption 挂钩中添加互斥组
- azure - Azure 目录中应用的回调 URL
- css - 文本溢出的悬停颜色:省略号卡在 Chrome 中
- javascript - 防止键盘在 datepicker mobile 上弹出
- python - 在输入中放置两个条件
- reactjs - 如何在 Semantic-UI-React 项目中导入 Google 字体?
- mysql - SQL - 查找具有未知但稍微相似的值的行?
- python-3.x - librosa.util.exceptions.ParameterError:单声道音频的形状无效:ndim=2,shape=(1025, 5341)
- python - Python 漂亮的打印嵌套对象
- javascript - 在模态中实现可折叠在单击时在列表中展开全部