Open History to see the last commit
1import {
2 ChangeDetectionStrategy,
3 Component,
4 ElementRef,
5 computed,
6 effect,
7 viewChild,
8} from '@angular/core'
9import { injectVirtualizer } from '@tanstack/angular-virtual'
10import {
11 QueryClient,
12 injectInfiniteQuery,
13 provideQueryClient,
14} from '@tanstack/angular-query-experimental'
15β
16async function fetchServerPage(
17 limit: number,
18 offset: number = 0,
19): Promise<{ rows: string[]; nextOffset: number }> {
20 const rows = new Array(limit)
21 .fill(0)
22 .map((e, i) => `Async loaded row #${i + offset * limit}`)
23β
24 await new Promise((r) => setTimeout(r, 500))
25β
26 return { rows, nextOffset: offset + 1 }
27}
28β
29@Component({
30 selector: 'infinite-scroll',
31 standalone: true,
32 changeDetection: ChangeDetectionStrategy.OnPush,
33 template: `
34 <p>
35 This infinite scroll example uses Angular Query's injectInfiniteScroll
36 function to fetch infinite data from a posts endpoint and then a
37 rowVirtualizer is used along with a loader-row placed at the bottom of the
38 list to trigger the next page to load.
39 </p>
40 @if (query.isLoading()) {
41 <p>Loading...</p>
42 } @else if (query.isError()) {
43 <span>Error: {{ query.error()!.message }}</span>
44 } @else {
45 <div #scrollElement class="list scroll-container">
46 <div
47 style="position: relative; width: 100%;"
48 [style.height.px]="virtualizer.getTotalSize()"
49 >
50 @for (row of virtualizer.getVirtualItems(); track row.index) {
51 <div
52 [class.list-item-even]="row.index % 2 === 0"
53 [class.list-item-odd]="row.index % 2 !== 0"
54 style="position: absolute; top: 0; left: 0; width: 100%;"
55 [style.height.px]="row.size"
56 [style.transform]="'translateY(' + row.start + 'px)'"
57 >
58 {{
59 row.index > allRows().length - 1
60 ? query.hasNextPage()
61 ? 'Loading more...'
62 : 'Nothing more to load'
63 : allRows()[row.index]
64 }}
65 </div>
66 }
67 </div>
68 </div>
69 }
70 @if (query.isFetching() && !query.isFetchingNextPage()) {
71 <div>Background Updating...</div>
72 }
73 `,
74 styles: `
75 .scroll-container {
76 height: 500px;
77 width: 100%;
78 overflow: auto;
79 }
80 `,
81 providers: [provideQueryClient(new QueryClient())],
82})
83export class InfiniteScrollComponent {
84 query = injectInfiniteQuery(() => ({
85 queryKey: ['rows'],
86 queryFn: ({ pageParam }) => fetchServerPage(10, pageParam),
87 initialPageParam: 0,
88 getNextPageParam: (_lastGroup, groups) => groups.length,
89 }))
90β
91 allRows = computed(
92 () => this.query.data()?.pages.flatMap((d) => d.rows) ?? [],
93 )
94β
95 scrollElement = viewChild<ElementRef<HTMLDivElement>>('scrollElement')
96β
97 virtualizer = injectVirtualizer(() => ({
98 scrollElement: this.scrollElement(),
99 count: this.query.hasNextPage()
100 ? this.allRows().length + 1
101 : this.allRows().length,
102 estimateSize: () => 100,
103 overscan: 5,
104 }))
105β
106 #fetchNextPage = effect(() => {
107 const lastItem =
108 this.virtualizer.getVirtualItems()[
109 this.virtualizer.getVirtualItems().length - 1
110 ]
111 if (!lastItem) {
112 return
113 }
114 if (
115 lastItem.index >= this.allRows().length - 1 &&
116 this.query.hasNextPage() &&
117 !this.query.isFetchingNextPage()
118 ) {
119 this.query.fetchNextPage()
120 }
121 })
122}
123β
124@Component({
125 selector: 'app-root',
126 standalone: true,
127 imports: [InfiniteScrollComponent],
128 template: '<infinite-scroll />',
129})
130export class AppComponent {}