Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Scroll last element of ngFor loop into view

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can scroll the new entry into view by setting focus on it, as shown in this stackblitz.

  • 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 the QueryList.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;
}

Code:

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);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...