Chrome - 在将元素添加到 *ngFor 视图时始终向下滚动到最后一个元素

And*_*rit 4 css google-chrome twitter-bootstrap bootstrap-4 angular

我有一个带有视频列表的简单页面。在页面底部,我有“加载更多”按钮。如果用户单击该按钮,我会发出 http 请求并将数据添加到现有的视频数组中。

简化代码如下所示:

成分:

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');
    })
  }

}
Run Code Online (Sandbox Code Playgroud)

模板:

<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>
Run Code Online (Sandbox Code Playgroud)

有什么问题:

在加载更多项目后,Firefox 页面不会滚动,所以我看到了第一个新项目。在 chrome 中,页面会滚动到最后,所以我再次看到了最后一个新项目和“加载更多”按钮。

演示:

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

Lak*_*kur 6

您可以添加overflow-anchor:none类似的内容:-

<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>
Run Code Online (Sandbox Code Playgroud)

溢出锚性质使我们能够选择出滚动锚定,这是一个浏览器的功能旨在让内容到用户的当前位置DOM以上负荷不改变用户的位置,一旦该内容已满载。

我参考了这个答案 - https://css-tricks.com/almanac/properties/o/overflow-anchor/