Anchor

In-page links that highlight the section in view.

Installation

Import the class, and @use the entry point in your global styles: without it the component renders unstyled.

import { Component } from '@angular/core';
import { WrAnchor } from 'ngwr/anchor';

@Component({ imports: [WrAnchor] })
export class MyComponent {}

Demo

Pass links in document order; set offset to the height of a sticky header.

<wr-anchor [links]="links" [offset]="80" />

Introduction

Anchor watches the page scroll and highlights the closest section.

Usage

Basic

Pass an array of { id, label } and the component does the rest.

Advanced

Children render one level of nested links.

API

See the component reference below.

API

NameDescriptionTypeDefault
linksThe entries, in DOCUMENT ORDER — the scroll spy walks them top to bottom and stops at the first target below the cursor line, so a list in any other order highlights the wrong entry.readonly WrAnchorLink[][]
ariaLabelAccessible name for the navigation landmark. Falls back to anchor.label, then 'Table of contents' — it used to be that English string, hard-coded on the host, in a landmark a screen reader reads out on every page.string | nullnull
offsetPixel offset subtracted on scroll — for sticky headers.number0
hitAreaHighlight an item when its target's top is within this many px of the offset line.number80

Types

interface WrAnchorLink {
  id: string;
  label: string;
  children?: readonly WrAnchorLink[];
}
NameDescriptionTypeDefault
WrAnchorLinkOne entry in the rail.interface—
idrequiredTarget element id (without #).string—
labelrequiredVisible text.string—
childrenOne level of nested links.readonly WrAnchorLink[]—

CSS variables

Set these on the component's selector or a wrapper, not on :root: the defaults are declared on ngwr/anchor's own element.

VariableDefaultDeclared on
--wr-anchor-bordervar(--wr-border-base).wr-anchor
--wr-anchor-font-familyvar(--wr-font-family-base).wr-anchor
--wr-anchor-link-active-font-weightvar(--wr-font-weight-semibold).wr-anchor
--wr-anchor-link-font-sizevar(--wr-text-sm).wr-anchor
--wr-anchor-link-line-heightvar(--wr-leading-snug).wr-anchor
--wr-anchor-link-padding-xvar(--wr-space-sm).wr-anchor
--wr-anchor-link-padding-yvar(--wr-space-xs).wr-anchor
--wr-anchor-link-radiusvar(--wr-border-radius-sm).wr-anchor
--wr-anchor-list-gapvar(--wr-space-xs).wr-anchor
--wr-anchor-list-nested-margin-topvar(--wr-space-xs).wr-anchor

Dependencies

Built onWrScroll

See also