Skip to content
Source
Sign inSign up
TanStack/virtual
Open History to see the last commit

app.component.ts

97 lines2.7 KB

1import {
2 ChangeDetectionStrategy,
3 Component,
4 ElementRef,
5 signal,
6 viewChild,
7} from '@angular/core'
8import { elementScroll, injectVirtualizer } from '@tanstack/angular-virtual'
9​
10function easeInOutQuint(t: number) {
11 return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t
13​
14@Component({
15 selector: 'app-root',
16 standalone: true,
17 changeDetection: ChangeDetectionStrategy.OnPush,
18 template: `
19 <p>
20 This smooth scroll example uses the <code>scrollToFn</code> to implement a
21 custom scrolling function for the methods like
22 <code>scrollToIndex</code> and <code>scrollToOffset</code>
23 </p>
24 <div>
25 <button (click)="scrollToRandomIndex()">
26 Scroll To Random Index ({{ randomIndex() }})
27 </button>
28 </div>
29 <br />
30 <div #scrollElement class="list scroll-container">
31 <div
32 style="position: relative; width: 100%;"
33 [style.height.px]="virtualizer.getTotalSize()"
34 >
35 @for (row of virtualizer.getVirtualItems(); track row.index) {
36 <div
37 [class.list-item-even]="row.index % 2 === 0"
38 [class.list-item-odd]="row.index % 2 !== 0"
39 style="position: absolute; top: 0; left: 0; width: 100%;"
40 [style.height.px]="row.size"
41 [style.transform]="'translateY(' + row.start + 'px)'"
42 >
43 Row {{ row.index }}
44 </div>
45 }
46 </div>
47 </div>
48 `,
49 styles: `
50 .scroll-container {
51 height: 200px;
52 width: 400px;
53 overflow: auto;
54 }
55 `,
56})
57export class AppComponent {
58 scrollElement = viewChild<ElementRef<HTMLDivElement>>('scrollElement')
59​
60 scrollingTime = signal(0)
61​
62 virtualizer = injectVirtualizer(() => ({
63 scrollElement: this.scrollElement(),
64 count: 10000,
65 estimateSize: () => 35,
66 overscan: 5,
67 scrollToFn: (offset, options, instance) => {
68 const duration = 1000
69 const start = this.scrollElement()!.nativeElement.scrollTop
70 const startTime = Date.now()
71 this.scrollingTime.set(startTime)
72​
73 const run = () => {
74 if (this.scrollingTime() !== startTime) return
75 const now = Date.now()
76 const elapsed = now - startTime
77 const progress = easeInOutQuint(Math.min(elapsed / duration, 1))
78 const interpolated = start + (offset - start) * progress
79​
80 if (elapsed < duration) {
81 elementScroll(interpolated, options, instance)
82 requestAnimationFrame(run)
83 } else {
84 elementScroll(interpolated, options, instance)
85 }
86 }
87 requestAnimationFrame(run)
88 },
89 }))
90​
91 randomIndex = signal(Math.floor(Math.random() * 10000))
92​
93 scrollToRandomIndex() {
94 this.virtualizer.scrollToIndex(this.randomIndex())
95 this.randomIndex.set(Math.floor(Math.random() * 10000))
96 }