Skip to main content
cngx-src documentation

CngxScrollSpy

DirectivePrimaryv0.1.0WCAG AA

projects/common/layout/scroll/scroll-spy.directive.ts

Import#

import { CngxScrollSpy } from '@cngx/common/layout'

Description#

Tracks which section is currently most visible in the viewport.

Observes a list of elements by their IDs using IntersectionObserver and reports the one with the highest intersection ratio as the active section. Ideal for scroll-based navigation highlighting and reading progress.

<nav [cngxScrollSpy]="['intro', 'features', 'pricing']"
     #spy="cngxScrollSpy">
  <a [class.active]="spy.activeId() === 'intro'" href="#intro">Intro</a>
  <a [class.active]="spy.activeId() === 'features'" href="#features">Features</a>
  <a [class.active]="spy.activeId() === 'pricing'" href="#pricing">Pricing</a>
</nav>

<section id="intro">…</section>
<section id="features">…</section>
<section id="pricing">…</section>

https://cngxjs.github.io/cngx/examples/#/common/layout/scroll-spy/scroll-based-navigation

Metadata#

Index#

Inputs#

root#string | null
input()

CSS selector for the scroll container root. null uses the viewport.

default null
rootMargin#string
input()

Root margin for the observer.

default '0px'
sections#string[]
input()Required

IDs of the sections to observe.

default { alias: 'cngxScrollSpy' }
threshold#number
input()

Minimum visibility ratio to consider a section as a candidate.

default 0.3

Outputs#

activeIdChange#string | null
output()

Emitted when the active section changes.

Instance Properties#

activeId#unknown
Readonly

ID of the section with the highest intersection ratio.

this.activeIdState.asReadonly()