Open History to see the last commit
1import {
2 ChangeDetectionStrategy,
3 Component,
4 ElementRef,
5 viewChild,
6} from '@angular/core'
7import { injectWindowVirtualizer } from '@tanstack/angular-virtual'
8β
9@Component({
10 selector: 'app-root',
11 standalone: true,
12 changeDetection: ChangeDetectionStrategy.OnPush,
13 template: `
14 <p>
15 In many cases, when implementing a virtualizer with a window as the
16 scrolling element, developers often find the need to specify a
17 "scrollMargin." The scroll margin is a crucial setting that defines the
18 space or gap between the start of the page and the edges of the list.
19 </p>
20 <h3>Window Scroller</h3>
21 <div #scrollElement class="list">
22 <div
23 style="position: relative; width: 100%;"
24 [style.height.px]="virtualizer.getTotalSize()"
25 >
26 @for (row of virtualizer.getVirtualItems(); track row.key) {
27 <div
28 #virtualItem
29 [class.list-item-even]="row.index % 2 === 0"
30 [class.list-item-odd]="row.index % 2 !== 0"
31 style="position: absolute; top: 0; left: 0; width: 100%;"
32 [style.height.px]="row.size"
33 [style.transform]="
34 'translateY(' +
35 (row.start - virtualizer.options().scrollMargin) +
36 'px)'
37 "
38 >
39 Row {{ row.index }}
40 </div>
41 }
42 </div>
43 </div>
44 `,
45 styles: `
46 .scroll-container {
47 height: 400px;
48 width: 400px;
49 overflow-y: auto;
50 contain: 'strict';
51 }
52 `,
53})
54export class AppComponent {
55 scrollElement = viewChild<ElementRef<HTMLDivElement>>('scrollElement')
56β
57 virtualizer = injectWindowVirtualizer(() => ({
58 count: 10000,
59 estimateSize: () => 35,
60 overscan: 5,
61 scrollMargin: this.scrollElement()?.nativeElement.offsetTop,
62 }))
63}