Angular provides a convenient alternative to document.getElementById
through its built-in API: @ViewChildren.
To improve organization, consider extracting the inline template into a new component.
Template
<button (click)="scrollToBottom()">Scroll to last comment</button>
<app-comment [title]="comment.title" *ngFor="let comment of comments$ | async">
</app-comment>
<button (click)="scrollToTop()">Scroll to 1st Comment</button>
Utilize ViewChildren in the Component to access the collection of CommentComponents represented by a QueryList.
If direct access to HTML elements is needed, configure @ViewChildren to read the ElementRef (
@ViewChildren(CommentComponent, { read: ElementRef })
).
Component
export class NotificationPostComponent extends PostComponent
implements OnInit, AfterViewInit {
comments$ = /* Stream of Comments */
@ViewChildren(CommentComponent, { read: ElementRef })
commentElementReferences: QueryList<ElementRef<HTMLElement>> | undefined;
}
You can mark each Comment Component with an attr-Binding
for identification if scrolling to a specific element is required.
Template
<app-comment
[title]="comment.title"
[attr.data-anchor]="comment.id"
*ngFor="let comment of comments$ | async"
>
</app-comment>
Add logic to your component to find and scroll to the desired Element based on ID or other attributes.
Component
private scrollToCommentById(id: string) {
if (!this.commentElementReferences) return;
const commentToScrollTo = this.commentElementReferences
.map((reference) => reference.nativeElement)
.find((element) => element.getAttribute('data-anchor') === id);
commentToScrollTo.scrollIntoView({ behavior: 'smooth' });
}
Trigger the scrolling mechanism upon navigation by connecting to the activated route.
ngAfterViewInit(): void {
// Listen to parameter changes in route
this.activatedRoute.paramMap
.pipe(
map((paramMap) => paramMap.get('id')),
filter((id) => !!id),
tap((id) => this.scrollToCommentById(id))
)
.subscribe();
}
Demo
Explore this StackBlitz @ViewChild Demo showcasing the setup, including the button that scrolls to a specific Comment by its ID.