htmlcssangularangular-cdk-virtual-scroll

How to resize angular cdk virtual viewport height when viewport size changes


I'm working on Angular cdk virtual viewport. Is there any way to automatically adjust height of scroll viewport?

So in my case When viewport size increases there is a blank space displays at the bottom of viewport, this is the similar example for the reference

https://stackblitz.com/edit/components-issue-mxahst?file=app%2Fapp.component.ts


Solution

  • You can call checkViewportSize on the CdkVirtualScrollViewport which will align your viewport to the new dimensions.

    First you take a reference to CdkVirtualScrollViewport in your component

    @ViewChild(CdkVirtualScrollViewport, { static: true })

    Then after the size change you call checkViewportSize (After Button is clicked)

      public remove() {
        this.showBottomBar = !this.showBottomBar;
        setTimeout((x) => {
          this.cdkVirtualScrollViewport.checkViewportSize();
        }, 10);
      }
    

    Note the little timeout, this is necessary because we want the dom changes (remove bottom-bar; render update) before we check the viewport size to align it.

    Full example based on your Stackblitz

    https://stackblitz.com/edit/components-issue-zl33lz?file=app%2Fapp.component.html,app%2Fapp.component.ts,app%2Fapp.component.scss