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);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…