Angular Table 虚拟化完全指南:用 TanStack Table + TanStack Virtual 实现超大表格渲染
Angular Table 虚拟化完全指南:用 TanStack Table + TanStack Virtual 实现超大表格渲染
本篇技术指南以 docs/framework/angular/guide/virtualization.md 为骨架,围绕 Angular Table 项目(@tanstack/angular-table)与 @tanstack/angular-virtual 的配合使用展开。虚拟化是一种渲染策略而非表格特性,本指南将带你掌握行虚拟化、列虚拟化、行列同时虚拟化以及无限滚动四种核心方案,结合仓库内真实示例源码,说明如何让几十万甚至上百万行、上万列的数据在保持 DOM 极小的前提下流畅渲染。
虚拟化在 TanStack Table 中的定位:渲染策略,而非表格特性
TanStack Table 的各个框架包(React、Vue、Solid、Svelte、Angular、Lit 等)本身不内置任何虚拟化 API 或特性。虚拟化是渲染层面的策略,不是表格的一个 feature,因此表格并不需要为虚拟化做任何特殊配置,也不需要特定的 row model。
在虚拟化场景中,TanStack Table 与虚拟化库各司其职:
- TanStack Table 负责构建 row models、columns、headers、cells、sizing、sorting、filtering 以及其余全部表格状态;
- TanStack Virtual(通过 Angular 适配器
@tanstack/angular-virtual)负责根据当前滚动位置决定渲染哪些 item 的索引; - 表格渲染器负责把这些虚拟索引映射回 rows、headers 和 cells。
也就是说:@tanstack/angular-virtual 只关心"滚动到哪、渲染哪些",而行的排序、过滤、分组等全部 row-model 计算仍然由 TanStack Table 完成。表格仍然"拥有"行、列和状态,虚拟化库只拥有滚动索引与尺寸测量(scroll indexes and measurements)。
何时应该使用虚拟化
当表格的行数、列数或两者同时都非常大时,才应该考虑虚拟化。虚拟化通过只渲染滚动视口内可见的条目加上一个较小的 overscan 缓冲,把 DOM 数量保持在很小的规模。
需要注意三个边界:
- 虚拟化不能替代服务端分页、过滤或排序。如果数据在客户端虚拟化,数据本身就必须完整存在于客户端。当数据集大到浏览器无法承载时,应改用服务端数据操作或无限滚动(见下文 虚拟化无限滚动)。
- 小表格无需虚拟化。常规渲染更简单,通常也更合适。
- 客户端虚拟化解决的是"渲染大量已有数据"的性能问题,不是"加载大量数据"的网络问题。
安装 TanStack Virtual 与表格基础搭建
安装 Angular 虚拟化适配器:
npm install @tanstack/angular-virtual
Angular 示例统一使用 @tanstack/angular-virtual 导出的 injectVirtualizer。表格本身的搭建与任何其他 v9 表格完全一致:用 tableFeatures() 声明特性,用 injectTable 创建表格,虚拟化不会改变表格的搭建方式。
import {
columnSizingFeature,
rowSortingFeature,
createSortedRowModel,
sortFns,
tableFeatures,
injectTable,
} from '@tanstack/angular-table'
import { injectVirtualizer } from '@tanstack/angular-virtual'
const features = tableFeatures({
columnSizingFeature,
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
sortFns,
})
export class App {
readonly table = injectTable(() => ({
features,
columns,
data: this.data(),
}))
}
从源码结构看,tableFeatures 是 Angular Table 声明式组合特性的统一入口,injectTable 则负责在 Angular 依赖注入环境中创建并持有表格实例;虚拟化代码(injectVirtualizer)与表格代码在组件中并列存在,二者通过 scrollElement、count 等配置建立联系。
虚拟化的基本模式
绝大多数虚拟化表格实现都遵循同一种模式:
- 创建一个固定高度的滚动容器;
- 把滚动元素(scroll element)传给 virtualizer;
- 用
table.getRowModel().rows或table.getVisibleLeafColumns()作为数据源列表; - 配置
count、estimateSize、overscan,以及可选的measureElement; - 只渲染虚拟条目;
- 用虚拟偏移量(virtual offsets)或占位 padding 保持完整滚动几何尺寸。
一个紧凑的行虚拟化示例:
readonly rows = computed(() => this.table.getRowModel().rows)
readonly rowVirtualizer = injectVirtualizer(() => ({
count: this.rows().length,
scrollElement: this.scrollContainer()?.nativeElement,
estimateSize: () => 33,
overscan: 5,
}))
<tbody
[style.height.px]="rowVirtualizer.getTotalSize()"
style="position: relative"
>
@for (virtualRow of rowVirtualizer.getVirtualItems(); track virtualRow.key) {
@let row = rows()[virtualRow.index];
<tr
[style.position]="'absolute'"
[style.transform]="'translateY(' + virtualRow.start + 'px)'"
[style.width]="'100%'"
>
@for (cell of row.getVisibleCells(); track cell.id) {
<td>
<ng-container *flexRenderCell="cell; let renderCell">
{{ renderCell }}
</ng-container>
</td>
}
</tr>
}
</tbody>
核心思想是:tbody 被赋予 rowVirtualizer.getTotalSize() 的完整虚拟高度(撑起滚动条),每一行用 position: absolute 配合 transform: translateY(virtualRow.start) 精确放置到对应位置,页面中只存在可见的几十行 DOM。
行虚拟化:让 DOM 与行数解耦
官方 Virtualized Rows 示例(同主题示例在 React、Solid、Svelte、Vue、Angular、Lit 各框架下均有提供)展示了如何在渲染海量行时保持 DOM 很小。
在示例 examples/angular/virtualized-rows/src/app/app.ts 中,组件用 signal 生成 20 万行数据,并提供一键 100 万行的压测按钮:
readonly data = signal(makeData(200_000))
// ...
readonly table = injectTable<typeof features, Person>(() => ({
features,
columns,
data: this.data(),
getRowId: (row) => String(row.id),
debugTable: true,
}))
// Important: Keep the virtualizer and the scroll container ref in the same component.
readonly rows = computed(() => this.table.getRowModel().rows)
// Important: Keep the row virtualizer as close to the rows as possible to avoid unnecessary work.
readonly rowVirtualizer = injectVirtualizer(() => ({
count: this.rows().length,
scrollElement: this.scrollContainer()?.nativeElement,
estimateSize: () => 33, // estimate row height for accurate scrollbar dragging
measureElement:
typeof window !== 'undefined' &&
navigator.userAgent.indexOf('Firefox') === -1
? (element) => element.getBoundingClientRect().height
: undefined,
overscan: 5,
}))
关键点解读:
count: this.rows().length:虚拟化器直接读取 TanStack Table 最终产出的 row model,排序、过滤、分组等计算全部由表格完成,虚拟化器只消费结果;estimateSize: () => 33:为滚动条拖拽提供初始行高估计值;measureElement:渲染后通过getBoundingClientRect().height精化真实行高,支持动态行高;由于 Firefox 对表格边框高度的测量方式不同,示例特意在 Firefox 中关闭动态测量(注释原文:measure dynamic row height, except in firefox because it measures table border height incorrectly);overscan: 5:视口上下各多渲染 5 行,避免测量收敛期间出现空白。
模板(examples/angular/virtualized-rows/src/app/app.html)中,tbody 被设置为 position: relative 并赋予 totalSize() 高度,每个 <tr> 通过 [attr.data-index]="virtualRow.index" 关联测量目标、通过 transform: translateY(...) 定位:
<tbody style="display: grid; position: relative" [style.height.px]="totalSize()">
@for (virtualRow of virtualRows(); track virtualRow.key) {
@let row = rows()[virtualRow.index];
<tr
[attr.data-index]="virtualRow.index"
[style.transform]="'translateY(' + virtualRow.start + 'px)'"
style="display: flex; position: absolute; width: 100%"
>
@for (cell of row.getAllCells(); track cell.id) {
<td style="display: flex" [style.width.px]="cell.column.getSize()">
<ng-container *flexRenderCell="cell; let renderCell">
{{ renderCell }}
</ng-container>
</td>
}
</tr>
}
</tbody>
注意该示例渲染单元格使用的是 row.getAllCells()。是否使用 getVisibleCells() 取决于示例是否需要"可见性感知"的单元格列表(涉及列可见性时用可见单元格,否则用全部单元格)。表格头部则通过 table.getHeaderGroups() 遍历,每个 <th> 用 header.getSize() 设置宽度,并支持点击排序(header.column.getToggleSortingHandler())。
列虚拟化:占位单元格保持滚动宽度
官方 Virtualized Columns 示例 展示同时渲染大量行与大量列的场景。示例默认生成 1000 行 × 1000 列,并提供 1 万行、1 万列的压测按钮(常量定义见 examples/angular/virtualized-columns/src/app/app.ts):
const DEFAULT_ROW_COUNT = 1_000
const DEFAULT_COLUMN_COUNT = 1_000
const STRESS_ROW_COUNT = 10_000
const STRESS_COLUMN_COUNT = 10_000
列虚拟化使用当前可见列列表:
readonly visibleColumns = computed(() => this.table.getVisibleLeafColumns())
列虚拟化器按水平方向配置:
readonly columnVirtualizer = injectVirtualizer<
HTMLDivElement,
HTMLTableCellElement
>(() => ({
count: this.visibleColumns().length,
scrollElement: this.scrollContainer()?.nativeElement,
estimateSize: (index) => this.visibleColumns()[index].getSize(), // estimate width of each column for accurate scrollbar dragging
horizontal: true,
overscan: 3, // how many columns to render on each side off screen each way (adjust this for performance)
}))
与行虚拟化不同,列虚拟化采用另一种渲染策略:不是绝对定位每一列,而是在左右两侧各添加一个"假"的占位单元格(spacer cell),用 padding 撑开水平滚动宽度:
readonly virtualPaddingLeft = computed(() => {
const virtualColumns = this.virtualColumns()
return virtualColumns.length ? (virtualColumns[0]?.start ?? 0) : undefined
})
readonly virtualPaddingRight = computed(() => {
const virtualColumns = this.virtualColumns()
return virtualColumns.length
? this.columnVirtualizer.getTotalSize() -
(virtualColumns[virtualColumns.length - 1]?.end ?? 0)
: undefined
})
在 examples/angular/virtualized-columns/src/app/app.html 中,表头与单元格两侧都渲染占位 <th> / <td>,中间只挂载虚拟列:
<tr style="display: flex; width: 100%">
@if (virtualPaddingLeft()) {
<!-- fake empty column to the left for virtualization scroll padding -->
<th style="display: flex" [style.width.px]="virtualPaddingLeft()"></th>
}
@for (virtualColumn of virtualColumns(); track virtualColumn.key) {
@let header = headerGroup.headers[virtualColumn.index];
<th style="display: flex; position: relative" [style.width.px]="header.getSize()">
...
</th>
}
@if (virtualPaddingRight()) {
<!-- fake empty column to the right for virtualization scroll padding -->
<th style="display: flex" [style.width.px]="virtualPaddingRight()"></th>
}
</tr>
单元格部分通过 @let visibleCells = row.getVisibleCells(); 与 @let cell = visibleCells[virtualColumn.index]; 完成虚拟列索引到真实单元格的映射。
这种占位方案让行仍然保持表格式的渲染结构,从而允许动态行高测量继续正常工作。该示例同时演示了列宽调整的联动:当列被拖拽调整尺寸后,虚拟化器的滚动数学必须与渲染宽度保持同步,示例用 effect 监听 table.atoms.columnSizing 变化并调用 columnVirtualizer.measure() 重新测量:
// re-measure virtual column widths when a column is resized so the
// virtualizer's scroll math stays in sync with the rendered widths
private readonly measureOnColumnResize = effect(() => {
void this.table.atoms.columnSizing.get()
untracked(() => this.columnVirtualizer.measure())
})
表头单元格同时内置了列宽拖拽手柄(header.getResizeHandler())、双击重置宽度(header.column.resetSize())等交互,columnResizeMode: 'onChange' 使调整即时生效。
行与列同时虚拟化
官方 virtualized-columns 示例在虚拟化列的同时也虚拟化了行。两种虚拟化各司其职、相互正交:
- 行虚拟化器控制垂直定位与 tbody 总高度(
rowVirtualizer.getTotalSize()); - 列虚拟化器控制水平方向的表头/单元格渲染与左右占位单元格;
virtualRow.index映射到rows[virtualRow.index];virtualColumn.index映射到visibleCells[virtualColumn.index]。
务必始终用虚拟索引去索引"当前"的行列表和列列表。当排序、过滤、分页、分组或列可见性发生变化时,必须基于最新表格状态重新计算虚拟行与虚拟列。rows() 与 visibleColumns() 都是 computed,表格状态更新后它们会同步失效并重算,从而保证 @let row = rows()[virtualRow.index] 这类索引始终与虚拟条目一一对应。
虚拟化无限滚动:虚拟化 + 渐进式取数
官方 Virtualized Infinite Scrolling 示例 把行虚拟化与渐进式数据拉取结合,适合数据集无法一次性载入浏览器的场景。Angular 无限滚动模式可以使用 TanStack Query,也可以使用任何其他数据获取层——示例本身实现了一个内置的 fetchData 模拟分页接口。
通用模式如下:
- 获取一页数据;
- 把已获取的页扁平化(flatten)进表格
data; - 对已加载的行做行虚拟化;
- 监听表格容器的滚动事件;
- 当用户滚近底部时拉取下一页。
示例的数据流在 examples/angular/virtualized-infinite-scrolling/src/app/app.ts 中清晰可见:
readonly pages = signal<Array<PersonApiResponse>>([])
readonly flatData = computed(() => this.pages().flatMap((page) => page.data))
readonly totalDBRowCount = computed(
() => this.pages()[0]?.meta?.totalRowCount ?? 0,
)
readonly totalFetched = computed(() => this.flatData().length)
表格的 data 直接绑定 flatData(),已加载多少行就渲染多少行,虚拟化器则始终以当前 rows 为 count:
readonly table = injectTable<typeof features, Person>(() => ({
features,
data: this.flatData(),
columns,
state: {
sorting: this.sorting(),
},
onSortingChange: (updater) => this.handleSortingChange(updater),
manualSorting: true,
debugTable: true,
}))
滚动触底判断由容器上的 (scroll) 事件驱动(examples/angular/virtualized-infinite-scrolling/src/app/app.html 中 #scrollContainer 绑定了 (scroll)="fetchMoreOnBottomReached(scrollContainer)"):
fetchMoreOnBottomReached(containerRefElement?: HTMLDivElement) {
if (containerRefElement) {
const { scrollHeight, scrollTop, clientHeight } = containerRefElement
// once the user has scrolled within 500px of the bottom of the table, fetch more data if we can
if (scrollHeight - scrollTop - clientHeight < 500) {
void this.fetchNextPage()
}
}
}
fetchNextPage 内置了防重入与终止保护:isFetching() 为真时直接返回,totalFetched() >= totalDBRowCount() 时停止;requestId 计数器确保旧的异步响应不会覆盖新请求的结果:
async fetchNextPage() {
if (this.isFetching() || this.totalFetched() >= this.totalDBRowCount()) {
return
}
const requestId = this.requestId
this.isFetching.set(true)
const page = await fetchData(
this.pages().length * fetchSize,
fetchSize,
this.sorting(),
)
if (requestId !== this.requestId) return
this.pages.update((pages) => [...pages, page])
this.isFetching.set(false)
}
如果排序由服务端处理,必须开启手动排序(manualSorting: true),这样取回的数据反映的是整个后端数据集而非仅当前已加载的行。当排序变化导致已取数据集被整体替换时,通过 rowVirtualizer.scrollToIndex(0) 把滚动条带回顶部:
handleSortingChange(updater: Updater<SortingState>) {
this.sorting.set(functionalUpdate(updater, this.sorting()))
if (this.table.getRowModel().rows.length) {
this.rowVirtualizer.scrollToIndex(0)
}
}
首次加载通过 effect 监听 sorting() 变化触发 loadFirstPage,isLoading() 状态下模板只显示 Loading...,避免空数据阶段渲染空表格。
动态行高:estimateSize 与 measureElement 配合
当内容可能换行或展开时,动态行高很有用,但它比固定行高复杂得多。原则是:先用 estimateSize 提供初始猜测,再用 measureElement 精化真实高度。
estimateSize: () => 33
在 Angular 中,向 injectVirtualizer 传入 measureElement 函数,并在每个渲染行上设置 data-index,让虚拟化器能把测量结果关联到正确的条目。这正是 Virtualized Rows 示例 的做法(该配置同时出现在上述三个 Angular 示例中):
readonly rowVirtualizer = injectVirtualizer(() => ({
count: this.rows().length,
scrollElement: this.scrollContainer()?.nativeElement,
estimateSize: () => 33,
// measure dynamic row height, except in firefox because it measures table border height incorrectly
measureElement:
typeof window !== 'undefined' &&
navigator.userAgent.indexOf('Firefox') === -1
? (element) => element.getBoundingClientRect().height
: undefined,
overscan: 5,
}))
<tr
[attr.data-index]="virtualRow.index"
[style.transform]="'translateY(' + virtualRow.start + 'px)'"
></tr>
overscan帮助避免测量收敛期间出现空白区域:刚渲染时各行高度仍是估计值,多渲染几行可作为缓冲;- 如果每一行都有已知的固定高度,应跳过动态测量,直接使用固定高度估计值(如
estimateSize: () => 33),这通常是最省性能的方案; - 动态测量场景下,行间交替使用绝对定位与 transform 位移,因此各行的实际位置由虚拟化器根据累计测量值计算,这也是为什么固定
data-index关联测量至关重要。
粘性表头与语义化表格标记
虚拟化示例仍然使用语义化的 <table>、<thead>、<tbody>、<tr>、<td> 标签,但为了支持虚拟定位与粘性表头,表格布局 CSS 必须改变。
动态行虚拟化通常需要:
table {
display: grid;
}
thead {
display: grid;
position: sticky;
top: 0;
}
tr {
display: flex;
}
行被绝对定位在 position: relative 的 tbody 内,单元格用 flex 尺寸以匹配 column.getSize() 或 cell.column.getSize()。这在示例模板中体现为:<table style="display: grid">、<thead style="display: grid; position: sticky; top: 0; z-index: 1">、<tr style="display: flex; position: absolute; width: 100%">、<td style="display: flex" [style.width.px]="cell.column.getSize()">。
这是有意为之的设计:原生表格布局(table layout)无法很好地配合被独立定位的动态高度虚拟行。把表格改为 grid/flex 布局后,行可以脱离表格布局算法独立定位,单元格宽度也能精确跟随列的 getSize()。
性能建议
官方指南给出的性能建议,结合示例实现可归纳为:
- 让虚拟化器尽量靠近渲染虚拟条目的组件。虚拟化器与滚动容器引用放在同一组件(源码注释:Keep the virtualizer and the scroll container ref in the same component),行虚拟化器尽量靠近行渲染位置(Keep the row virtualizer as close to the rows as possible to avoid unnecessary work),避免每次滚动触发不必要的重渲染;
- 避免每次滚动都重渲染整个表格体。示例均使用
ChangeDetectionStrategy.OnPush,并把virtualRows()、totalSize()等包装为computed,滚动只影响可见行集合; - 在可能的情况下保持行、列和数据的引用稳定。用
signal持有 data/columns,更新时整体替换而非原地修改,让computed的依赖追踪可预期; - 有意识地使用
overscan。更大的 overscan 减少可见空白,更小的 overscan 减少 DOM 节点数量。行示例用 5,列示例用 3,并注明可按需调整; - 避免在超大虚拟化表格中使用昂贵的单元格渲染器。虚拟化只控制渲染数量,不降低单个单元格的成本;
- 先测生产构建再优化。开发模式构建通常比生产构建慢——Angular 示例页面顶部就明确提示 Virtualized rendering performance will be slightly degraded until this application is built for production;
- UI 允许时优先固定行高。固定高度可跳过
measureElement,让滚动数学更简单稳定; - 列虚拟化中统一使用
column.getSize()、header.getSize()与cell.column.getSize()获取宽度,保证表头与单元格宽度一致。
总结与源码导航
Angular Table 的虚拟化实践可以概括为一句话:表格状态归 TanStack Table,滚动与测量归 TanStack Virtual,渲染器负责把两者桥接起来。虚拟化不改变表格的任何配置,只是渲染层的一种策略选择。
本文涉及的关键源码路径:
- 官方指南原文:docs/framework/angular/guide/virtualization.md
- 行虚拟化示例:examples/angular/virtualized-rows/src/app/app.ts 与 app.html
- 列虚拟化示例:examples/angular/virtualized-columns/src/app/app.ts 与 app.html
- 无限滚动示例:examples/angular/virtualized-infinite-scrolling/src/app/app.ts 与 app.html
- 三个示例均配有端到端冒烟测试,可参见各示例目录下的
tests/e2e/smoke.spec.ts
需要实际运行示例时,进入对应示例目录(如 examples/angular/virtualized-rows)安装依赖后启动开发服务器即可体验 20 万行 / 100 万行压测;生产构建后再观察性能,结论会更加接近真实线上表现。