Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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><divclass="list-container"><divtabindex="1" #commentDivclass="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';
...    
exportclassAppComponent {

  @ViewChildren("commentDiv") commentDivs: QueryList<ElementRef>;

  comments = newArray<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);
  }
}

Post a Comment for "Scroll Last Element Of Ngfor Loop Into View"