1

I am searching for the correct way to correct to scroll in a page that will load dynamic information. These informations are asynchronous so to avoid my user seeing the whole page constructing itself I have a boolean flag like so :

<div *ngIf="loaded"> ... </div>

My problem is that I want to scroll to an anchor using the angular router, but that anchor doesn't exist yet at this moment because the load isn't finished.

The anchor :

<hr id="my_anchor">

the code I use to load the page and get to that anchor :

<a [routerLink]="['/some/route/', idParameter]" fragment="my_anchor">...</a>

1 Answer 1

0

You probably want to use virtual scrolling, available through the Angular CDK:

https://material.angular.io/cdk/scrolling/examples

https://medium.com/codetobe/learn-how-to-us-virtual-scrolling-in-angular-7-51158dcacbd4

This approach dynamically loads only those components that are on screen, allowing you to load extremely large datasets.

It is also possible to code this manually using:

const el: any = document.elementFromPoint(x, y);

This Javascript function determines which HTMLElement is located at a specific x, y, coordinate and thereby determining which elements are on screen. Using this information you can wrap all items in a list like so:

<ng-container *ngFor="let data of datas">
  <ng-container *ngIf="data.isOnScreen">
    <app-my-component></app-my-component>
  </ng-container>
  <ng-container *ngIf="!data.isOnScreen">
    <div class="empty-div">&nbsp;</div>
  </ng-container>
</ng-container>

and style the empty-div to be the same size as a non empty div. This ensures that scrolling works. I got this working well. However, no doubt the CDK makes this a whole world smoother and easier.

The only benefit with my custom approach is it gives you total control. You can easily use:

list.scrollTop = 999;

to scroll to any position in the list, thus supporting anchors (where list is the HTML list element that will scroll). Not for the feint hearted though, would only recommend this for confident coders.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.