Angular虚拟滚动显示问题
创始人
2024-10-30 10:31:02
0

在Angular中使用虚拟滚动时,有时候会遇到显示问题。这些问题通常是出现在滚动中的元素大小不一致的情况下。在此情况下,因为使用了虚拟滚动,所以只有少量的元素会被渲染。这样的话,它们的大小会影响渲染出来的元素的数量。

为了解决这个问题,我们可以对VirtualScrollStrategy进行扩展,在该扩展中,我们可以实现自己对ElementRef和ViewContainerRef的处理方式,从而确保元素会正确的被渲染出来。以下是一个示例:

import {CollectionViewer, DataSource, ListRange} from '@angular/cdk/collections';
import { BehaviorSubject, Observable, of } from 'rxjs';
import {catchError, finalize} from 'rxjs/operators';
import { ElementRef, Injectable, OnDestroy, ViewContainerRef } from '@angular/core';
import { CdkVirtualScrollViewport, VirtualScrollStrategy } from '@angular/cdk/scrolling';

@Injectable()
export class CustomVirtualScrollStrategy implements VirtualScrollStrategy, OnDestroy {
  private indexChange = new BehaviorSubject(0);
  private dataStream = new BehaviorSubject([]);
  private pooledPages = new Map();

  private viewRef: any;

  private snappedIndex = 0;

  constructor(private elementRef: ElementRef, private viewContainer: ViewContainerRef) {
    this.elementRef.nativeElement.style.overflow = 'auto';
  }

  ngOnDestroy(): void {}

  scrolled(index: number): void {
    const snappedIndex = this.getSnappedIndex(index);
    if (this.snappedIndex !== snappedIndex) {
        this.snappedIndex = snappedIndex;
        const maxIndex = this.viewRef.getDataLength() - 1;
        const start = Math.max(0, this.snappedIndex - 20);
        const end = Math.min(this.snappedIndex + 20, maxIndex);
        const pages = new Set();
        for (let i = start; i <= end; i++) {
            const pageIndex = Math.floor(i / this.viewRef.getPageSize());
            pages.add(pageIndex);
        }
        pages.forEach(page => this.fetchPage(page));
    }
  }

  attach(viewRef: any): void {
    this.viewRef = viewRef;
    this.viewContainer.createEmbeddedView(viewRef.templateRef);
  }

  detach(): void {
    this.viewContainer.clear();
    this.viewRef = null;
  }

  onDataLengthChanged(): void {
    this.indexChange.next(this.getAdjustedIndex(this.sn

相关内容

热门资讯

两分钟了解!打哈儿麻将辅助软件... 两分钟了解!打哈儿麻将辅助软件!果然是真的有辅助app(有挂分析)-哔哩哔哩1、每一步都需要思考,不...
五分钟了解!好友赣南辅助!果然... 五分钟了解!好友赣南辅助!果然是真的有辅助app(真的有挂)-哔哩哔哩;1、这是跨平台的好友赣南辅助...
第四分钟了解!小程序家乡大贰脚... 第四分钟了解!小程序家乡大贰脚本!其实是真的有辅助攻略(发现有挂)-哔哩哔哩1、下载好小程序家乡大贰...
一分钟了解!钱塘十三水辅助!其... 一分钟了解!钱塘十三水辅助!其实是真的有辅助工具(有人有挂)-哔哩哔哩1、下载好钱塘十三水辅助正确养...
1分钟了解!潮汕掌上娱破解!本... 1分钟了解!潮汕掌上娱破解!本来一直总是有辅助技巧(竟然有挂)-哔哩哔哩1、潮汕掌上娱破解破解器简单...
9分钟了解!财神十三张有挂辅助... 9分钟了解!财神十三张有挂辅助吗!一直真的有辅助app(确实有挂)-哔哩哔哩;1、下载好财神十三张有...
第三分钟了解!丽水都莱有辅助吗... 第三分钟了解!丽水都莱有辅助吗!切实真的有辅助插件(真的有挂)-哔哩哔哩进入游戏-大厅左侧-新手福利...
第7分钟了解!天天贵阳app修... 第7分钟了解!天天贵阳app修改器!本来存在有辅助软件(证实有挂)-哔哩哔哩1、天天贵阳app修改器...
第九分钟了解!微信开发辅助工具... 第九分钟了解!微信开发辅助工具!本来是真的有辅助插件(有挂总结)-哔哩哔哩1、第九分钟了解!微信开发...
5分钟了解!潮汕雀友百度贴吧辅... 5分钟了解!潮汕雀友百度贴吧辅助软件!一贯是有辅助方法(有挂透视)-哔哩哔哩一、潮汕雀友百度贴吧辅助...