首页 > 解决方案 > 将 ngFor 循环的最后一个元素滚动到视图中

问题描述

我的用户可以将条目添加到滚动列表的底部。但是,添加条目时滚动条不会自动向下移动,因此用户看不到他们新添加的条目。如何让我的滚动条始终处于向下滚动最多的位置以显示最新条目(使用 Angular 5)?

标签: javascripthtmlangular

解决方案


您可以通过设置焦点将新条目滚动到视图中,如此 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);
  }
}

推荐阅读