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

Fir*_*nks 3 html javascript angular

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

Con*_*Fan 10

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

  • 如果 item 元素具有tabindex属性,则它们可以被聚焦
  • 它们还应该具有 style 属性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>
Run Code Online (Sandbox Code Playgroud)

CSS:

div.list-container {
  height: 150px; 
  overflow: auto;
  border: solid 1px black;
}

div.comment-item {
  outline: none;
}
Run Code Online (Sandbox Code Playgroud)

代码:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道这已经晚了 2 年,而且我知道这个网站对于荣誉帖子来说很糟糕......但我想感谢你!我花了将近一周的时间试图让我的聊天消息滚动到最后一条消息,这是唯一对我有用的方法。 (2认同)