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、不需要AI权限,...
据报道!wepoker轻量版有... 据报道!wepoker轻量版有透视吗,德普之星app安卓版破解版,一贯真的是有挂(有挂方针)亲,关键...
一分钟揭秘!长乐互娱软件助手,... 一分钟揭秘!长乐互娱软件助手,欢聚水鱼辅助,详细教程(有挂头条)1、让任何用户在无需长乐互娱软件助手...
现有说明如下!德普之星透视辅助... 现有说明如下!德普之星透视辅助软件,德扑圈透视,果然真的有挂(有挂规律)德普之星透视辅助软件能透视中...
今日公布!琼戏互娱破解版,雀友... 今日公布!琼戏互娱破解版,雀友圈斗地主有挂,详细器(有挂头条);1、超多福利:超高返利,海量正版游戏...
方法辅助挂!哈糖大菠萝辅助器,... 方法辅助挂!哈糖大菠萝辅助器,德普软件,竟然真的有挂(有人有挂)1、打开软件启动之后找到中间准星的标...
分享个大家!维系小程序雀神挂件... 分享个大家!维系小程序雀神挂件,潮汕来物几局游戏源码,详细工具(今日头条)1、很好的工具软件,可以解...
昨日!wepoker买脚本靠谱... 昨日!wepoker买脚本靠谱吗,德普之星怎么设置埋牌,好像是真的有挂(有挂透明挂)进入游戏-大厅左...
近年来!wepoker脚本,智... 近年来!wepoker脚本,智星德州插件怎么下载,本来确实有挂(有挂总结)1、玩家可以在智星德州插件...
无独有偶!wepoker插件辅... 无独有偶!wepoker插件辅助,德普之星辅助软件,好像是真的有挂(有挂助手)1、每一步都需要思考,...