提问者:小点点

将ngFor循环的最后一个元素滚动到视图中


我的用户可以将条目添加到滚动列表的底部。但是,滚动条在添加条目时不会自动下移,因此用户看不到他们新添加的条目。我如何保持我的滚动条总是在最向下滚动的位置,以显示最新的条目(使用角度5)?


共1个答案

匿名用户

您可以通过在新条目上设置focus将其滚动到视图中,如此StackBlitz所示。

  • 如果项元素具有tabindex属性
  • 则可以对其进行聚焦
  • 它们还应具有样式属性outline:none(删除焦点轮廓)
  • 应在项目元素上设置模板引用变量(例如#commentdiv)
  • 通过ViewChildrenQueryList.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);
  }
}