How to set the initial index (position) for the CdkVirtualScrollViewport in Angular 7

不羁岁月 提交于 2020-08-07 01:26:31

问题


I need the inital position of the cdk-virtual-scroll-viewport to be other than the first element / item of the list.

Now I found the scrollToIndex and scrollTo methods, but I only can get them to work when using it in the ngAfterViewChecked, which feels off.

  1. Can someone confirm that the using those methods in the ngAfterViewChecked is the right way of doing things?
  2. If not, show an alternative method / technique?

  @ViewChild(CdkVirtualScrollViewport) cdkVirtualScrollViewport: CdkVirtualScrollViewport;
  numbers: number[] = [];

  constructor() {
    for (let index = 0; index < 10000; index++) {
      this.numbers.push(index);
    }
  }

  ngAfterViewChecked() {
    this.cdkVirtualScrollViewport.scrollToIndex(2000);
  }
  <ul class="list">
    <cdk-virtual-scroll-viewport style="height:264px" itemSize="88">
      <ng-container *cdkVirtualFor="let n of numbers">
        <li style="height:88px">{{ n }}</li>
      </ng-container>
    </cdk-virtual-scroll-viewport>
  </ul>

回答1:


I have the same problem, I have a not so elegant solution

contentCheck = 0

ngAfterViewChecked() {
  if (this.contentCheck < 3) {
  this. cdkVirtualScrollViewport.scrollToIndex(4000);
  this.contentCheck++;
 }
}

After 3 checks the scrollToIndex works.




回答2:


Although not a perfect solution, you can achieve this behavior by combining afterViewInit with setTimeout:

ngAfterViewInit() {
    setTimeout(() => {
        this.cdkVirtualScrollViewport.scrollToIndex(50);
    });
}


来源:https://stackoverflow.com/questions/53269172/how-to-set-the-initial-index-position-for-the-cdkvirtualscrollviewport-in-angu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!