Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome - On adding elements to *ngFor view always scroll down to last element

I have simple page with list of videos. At bottom of page I have button "Load more". If user click that button I make http request and add data to existing array of videos.

Simplified code looks like this:

Component:

export class AppComponent implements OnInit {
  public videoList = [];

  constructor(private appService: AppService) {}

  public ngOnInit(): void {
    this.loadVides();
  }

  public loadMore(): void {
    this.loadVides();
  }

  private loadVides(): void {
    this.appService.loadVideos().subscribe((videos) => {
      this.videoList = [...this.videoList, ...videos];
      console.log('Data was loaded');
    })
  }

}

Template:

<div *ngFor="let video of videoList">
  <div style="height: 100px;">{{video.name}}</div>
</div>  


<div class="d-flex justify-content-center mt-2 mb-4">
  <button class="btn btn-outline-danger btn-lg" (click)="loadMore()">Load more...</button>
</div>

What a problem is:

At firefox page is not scrolled after more items are loaded, so I see the first of the new items. And at chrome, the page is scrolled to the end, so I see the last new item and 'load more' button again.

Demo:

https://stackblitz.com/edit/angular-ivy-quwfxx?devtoolsheight=33&file=src/app/app.component.html

like image 328
Andurit Avatar asked Mar 01 '23 23:03

Andurit


1 Answers

You can add the overflow-anchor:none like so:-

<div *ngFor="let video of videoList">
  <div style="height: 100px;">{{video.name}}</div>
</div>  


<div style="overflow-anchor:none" class="d-flex justify-content-center mt-2 mb-4">
  <button class="btn btn-outline-danger btn-lg" (click)="loadMore()">Load more...</button>
</div>

The overflow-anchor property enables us to opt out of Scroll Anchoring, which is a browser feature intended to allow content to load above the user’s current DOM location without changing the user’s location once that content has been fully loaded.

I referred this for the answer - https://css-tricks.com/almanac/properties/o/overflow-anchor/

like image 199
Lakshya Thakur Avatar answered Mar 05 '23 05:03

Lakshya Thakur