将ngFor循环的最后一个元素滚动到视图中 [英] Scroll last element of ngFor loop into view
本文介绍了将ngFor循环的最后一个元素滚动到视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的用户可以将条目添加到滚动列表的底部.但是,添加条目时滚动条不会自动向下移动,因此用户看不到他们新添加的条目.如何使滚动条始终保持在最向下滚动的位置以显示最新条目(使用Angular 5)?
My users can add entries to the bottom of a scrolling list. However, the scrollbar doesn't automatically move down when the entry is added, so the user can't see their newly added entry. How can I keep my scrollbar always in the most scrolled-down position to show the latest entries (using Angular 5)?
推荐答案
You can scroll the new entry into view by setting focus on it, as shown in this stackblitz.
- 如果item元素具有
tabindex
属性 ,则可以对其进行聚焦 - 它们还应该具有样式属性
outline:none
(以删除焦点轮廓) - 应在item元素上设置模板参考变量(例如
#commentDiv
) - 使用
ViewChildren
和QueryList.changes
事件 监视对列表的更改. - 检测到列表发生更改时,焦点将设置在列表的最后一个元素上
- The item elements can be focused if they have a
tabindex
attribute - They should also have the style attribute
outline: none
(to remove the focus outline) - A template reference variable should be set on the item elements (e.g.
#commentDiv
) - The changes to the list are monitored with
ViewChildren
and theQueryList.changes
event - When a change on the list is detected, the focus is set on the last element of the list
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);
}
}
这篇关于将ngFor循环的最后一个元素滚动到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文