0
0
AngularHow-ToBeginner · 3 min read

How to Create Infinite Scroll in Angular: Simple Guide

To create infinite scroll in Angular, use the IntersectionObserver API to detect when the user scrolls near the bottom of a list and then load more data dynamically. This approach avoids heavy event listeners and improves performance by loading items only when needed.
📐

Syntax

Infinite scroll in Angular typically involves these parts:

  • Template: A list to display items and a sentinel element to observe scrolling.
  • Component: Logic to fetch data and detect when to load more.
  • IntersectionObserver: A browser API to watch when the sentinel enters the viewport.
typescript
import { Component, ElementRef, OnInit, ViewChild, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-infinite-scroll',
  template: `
    <div *ngFor="let item of items">{{ item }}</div>
    <div #anchor></div>
  `
})
export class InfiniteScrollComponent implements OnInit, OnDestroy {
  items = [];
  @ViewChild('anchor', { static: true }) anchor: ElementRef<HTMLElement>;
  private observer: IntersectionObserver;

  ngOnInit() {
    this.loadItems();
    this.observer = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting) {
        this.loadItems();
      }
    });
    this.observer.observe(this.anchor.nativeElement);
  }

  ngOnDestroy() {
    this.observer.disconnect();
  }

  loadItems() {
    // Fetch or generate more items
  }
}
💻

Example

This example shows a simple infinite scroll that loads 20 more items each time you reach the bottom.

typescript
import { Component, ElementRef, OnInit, ViewChild, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-infinite-scroll',
  template: `
    <div *ngFor="let item of items" style="padding: 10px; border-bottom: 1px solid #ccc;">
      Item {{ item }}
    </div>
    <div #anchor style="height: 30px;"></div>
  `
})
export class InfiniteScrollComponent implements OnInit, OnDestroy {
  items: number[] = [];
  @ViewChild('anchor', { static: true }) anchor: ElementRef<HTMLElement>;
  private observer: IntersectionObserver;
  private batch = 20;
  private lastIndex = 0;

  ngOnInit() {
    this.loadItems();
    this.observer = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting) {
        this.loadItems();
      }
    });
    this.observer.observe(this.anchor.nativeElement);
  }

  ngOnDestroy() {
    this.observer.disconnect();
  }

  loadItems() {
    for (let i = 1; i <= this.batch; i++) {
      this.items.push(this.lastIndex + i);
    }
    this.lastIndex += this.batch;
  }
}
Output
A vertical list of items labeled 'Item 1' to 'Item 20' initially, then more items load automatically as you scroll down.
⚠️

Common Pitfalls

1. Not disconnecting the observer: Forgetting to disconnect the IntersectionObserver can cause memory leaks.

2. Loading too many items at once: This can slow down the page; load in small batches.

3. Using scroll events instead of IntersectionObserver: Scroll events fire too often and hurt performance.

typescript
/* Wrong: Using scroll event listener */
window.addEventListener('scroll', () => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
    loadMoreItems();
  }
});

/* Right: Using IntersectionObserver */
const observer = new IntersectionObserver(entries => {
  if (entries[0].isIntersecting) {
    loadMoreItems();
  }
});
observer.observe(anchorElement);
📊

Quick Reference

  • Use IntersectionObserver to detect when to load more items.
  • Load items in small batches to keep UI responsive.
  • Always disconnect the observer on component destroy.
  • Use a sentinel element at the bottom of your list to observe.

Key Takeaways

Use IntersectionObserver to efficiently detect when to load more items in Angular infinite scroll.
Load data in small batches to keep the app fast and responsive.
Always disconnect the IntersectionObserver to prevent memory leaks.
Avoid scroll event listeners for infinite scroll due to performance issues.
Place a sentinel element at the list bottom to trigger loading more items.