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

相关内容

热门资讯

透视黑科技"wepo... 透视黑科技"wepoker科技辅助器"详细辅助必赢教程(透视脚本免费app教程)是一款可以让一直输的...
透视好友房"wepo... 1、透视好友房"wepoker脚本下载"详细辅助玩家教程(免费脚本技巧);详细教程。2、wepoke...
透视有挂"aapok... 1、透视有挂"aapoker脚本"详细辅助必备教程(安装透视软件神器);详细教程。2、aapoker...
透视线上"wepok... 1、透视线上"wepoker私人局辅助挂"详细辅助黑科技教程(游戏下载软件)2、进入游戏-大厅左侧-...
透视安装"红龙pok... 1、透视安装"红龙poker辅助平台"详细辅助软件教程(手机版透视脚本技巧)。2、红龙poker辅助...
透视教学"约局吧德州... 透视教学"约局吧德州透视"详细辅助力荐教程(有机器人教程)关于约局吧德州透视机制的,其中提到了后台系...
透视玄学"wepok... 透视玄学"wepoker有辅助插件吗"详细辅助细节揭秘(如何下载安装包透明)1、点击下载安装,微扑克...
透视挂透视"德普之星... 此外,数据分析德州(德普之星私人局辅助免费)辅助神器app还具备辅助透视行为开挂功能,通过对客户德普...
透视了解"pokem... 透视了解"pokemomo辅助工具"详细辅助可靠技巧(黑侠破解技巧)1、点击下载安装,微扑克wpk插...
透视免费"wepok... 透视免费"wepoker私人定制透视"详细辅助总结教程(俱乐部辅助器透明);科技安装教程;13670...