Open History to see the last commit
1import {
2 ChangeDetectionStrategy,
3 Component,
4 ElementRef,
5 computed,
6 viewChild,
7} from '@angular/core'
8import { faker } from '@faker-js/faker'
9import {
10 injectVirtualizer,
11 defaultRangeExtractor,
12} from '@tanstack/angular-virtual'
13β
14const groupedNames: Record<string, string[]> = {}
15β
16Array.from({ length: 1000 })
17 .map(() => faker.person.firstName())
18 .sort()
19 .forEach((name) => {
20 const char = name[0]
21 if (!groupedNames[char]) {
22 groupedNames[char] = []
23 }
24 groupedNames[char].push(name)
25 })
26const groups = Object.keys(groupedNames)
27const rows = groups.reduce(
28 (acc: string[], k) => [...acc, k, ...groupedNames[k]],
29 [],
30)
31const stickyIndexes = groups.map((gn) => rows.findIndex((n) => n === gn))
32const stickyIndexesSet = new Set(stickyIndexes)
33const reversedStickyIndexes = [...stickyIndexes].reverse()
34β
35@Component({
36 selector: 'app-root',
37 standalone: true,
38 changeDetection: ChangeDetectionStrategy.OnPush,
39 template: `
40 <div #scrollElement class="list scroll-container">
41 <div
42 style="position: relative; width: 100%;"
43 [style.height.px]="virtualizer.getTotalSize()"
44 >
45 @for (row of virtualizer.getVirtualItems(); track row.index) {
46 <div
47 [attr.data-index]="row.index"
48 style="top: 0; left: 0; width: 100%; background: #fff"
49 [style.zIndex]="isSticky(row.index) ? 1 : null"
50 [style.borderBottom]="
51 isSticky(row.index) ? '1px solid #ddd' : 'none'
52 "
53 [style.position]="isActiveSticky(row.index) ? 'sticky' : 'absolute'"
54 [style.height.px]="row.size"
55 [style.transform]="
56 isActiveSticky(row.index)
57 ? null
58 : 'translateY(' + row.start + 'px)'
59 "
60 >
61 {{ rows[row.index] }}
62 </div>
63 }
64 </div>
65 </div>
66 `,
67 styles: `
68 .scroll-container {
69 height: 300px;
70 width: 400px;
71 overflow: auto;
72 }
73 `,
74})
75export class AppComponent {
76 rows = rows
77β
78 isSticky = (index: number) => stickyIndexesSet.has(index)
79β
80 scrollElement = viewChild<ElementRef<HTMLDivElement>>('scrollElement')
81β
82 virtualizer = injectVirtualizer(() => ({
83 scrollElement: this.scrollElement(),
84 count: this.rows.length,
85 estimateSize: () => 50,
86 rangeExtractor: (range) => {
87 const next = new Set([
88 reversedStickyIndexes.find((index) => range.startIndex >= index)!,
89 ...defaultRangeExtractor(range),
90 ])
91 return [...next].sort((a, b) => a - b)
92 },
93 }))
94β
95 activeStickyIndex = computed(() => {
96 return this.virtualizer.getVirtualItems()[0]?.index
97 })
98β
99 isActiveSticky = (index: number) => this.activeStickyIndex() === index
100}