From 0d958cb33141335781b51a3897c8428f84a368cf Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:16:04 -0500 Subject: [PATCH 1/4] Add failing specs for a lesson scroll-spy nav and lesson 10 Every lesson should get an "On this page" nav over its sections that marks the one in view. ScrollSpy, LessonSection and lesson 10 don't exist yet; the every-lesson spec fails nine times with no nav at all. --- .../lessons/lesson-10-directives.spec.ts | 55 ++++++++++++++ .../thoughts-content/lessons/lesson.spec.ts | 69 +++++++++++++++++ .../thoughts-content/lessons/lessons.spec.ts | 17 +++++ .../lessons/scroll-spy.spec.ts | 76 +++++++++++++++++++ src/test/fake-intersection-observer.ts | 52 +++++++++++++ 5 files changed, 269 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-10-directives.spec.ts create mode 100644 src/app/thoughts-content/lessons/lesson.spec.ts create mode 100644 src/app/thoughts-content/lessons/lessons.spec.ts create mode 100644 src/app/thoughts-content/lessons/scroll-spy.spec.ts create mode 100644 src/test/fake-intersection-observer.ts diff --git a/src/app/thoughts-content/lessons/lesson-10-directives.spec.ts b/src/app/thoughts-content/lessons/lesson-10-directives.spec.ts new file mode 100644 index 0000000..69c1794 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-10-directives.spec.ts @@ -0,0 +1,55 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { LESSON_PAGES } from './lessons'; +import { Lesson10Directives } from './lesson-10-directives'; + +expect.extend(axeMatchers); + +describe('Lesson10Directives', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson10Directives] }).compileComponents(); + fixture = TestBed.createComponent(Lesson10Directives); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-10-directives']).toBeDefined(); + }); + + it('teaches at three levels, then pitfalls and interview questions', () => { + const headings = [...el.querySelectorAll('h2')].map((h) => h.textContent?.trim()); + expect(headings).toEqual( + expect.arrayContaining(['Simple', 'Intermediate', 'Expert', 'Pitfalls', 'Interview questions']), + ); + }); + + it('a custom structural directive adds and removes its template', async () => { + expect(el.querySelector('#demo-unless-content')).not.toBeNull(); + + el.querySelector('#demo-unless-toggle')!.click(); + await fixture.whenStable(); + expect(el.querySelector('#demo-unless-content')).toBeNull(); + + el.querySelector('#demo-unless-toggle')!.click(); + await fixture.whenStable(); + expect(el.querySelector('#demo-unless-content')).not.toBeNull(); + }); + + it('a host directive styles the component it is composed into, through an aliased input', async () => { + const select = el.querySelector('#demo-chip-color')!; + select.value = 'gold'; + select.dispatchEvent(new Event('change')); + await fixture.whenStable(); + + expect(el.querySelector('#demo-chip')!.style.backgroundColor).toBe('gold'); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson.spec.ts b/src/app/thoughts-content/lessons/lesson.spec.ts new file mode 100644 index 0000000..bf6d0bf --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson.spec.ts @@ -0,0 +1,69 @@ +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { FakeIntersectionObserver } from '../../../test/fake-intersection-observer'; +import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; + +expect.extend(axeMatchers); + +@Component({ + imports: [Lesson, LessonSection], + template: ` + +

Simple

+

First section.

+

Interview questions

+

Last section.

+
+ `, +}) +class Host {} + +describe('Lesson', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + let scrollIntoView: ReturnType; + + const tocButtons = () => [...el.querySelectorAll('nav[aria-label="On this page"] button')]; + + beforeEach(async () => { + FakeIntersectionObserver.install(); + scrollIntoView = vi.fn(); + Element.prototype.scrollIntoView = scrollIntoView; + fixture = TestBed.createComponent(Host); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + afterEach(() => FakeIntersectionObserver.uninstall()); + + it('gives each section heading an id taken from its text', () => { + expect([...el.querySelectorAll('h2')].map((h) => h.id)).toEqual(['simple', 'interview-questions']); + }); + + it('lists the sections in an "On this page" nav', () => { + expect(tocButtons().map((b) => b.textContent?.trim())).toEqual(['Simple', 'Interview questions']); + }); + + it('jumping to a section scrolls it into view and moves focus to it', () => { + tocButtons()[1].click(); + const heading = el.querySelector('#interview-questions')!; + expect(scrollIntoView.mock.contexts[0]).toBe(heading); + expect(document.activeElement).toBe(heading); + }); + + it('marks the section in view as the current location', async () => { + FakeIntersectionObserver.latest().report([ + { target: el.querySelector('#interview-questions')!, isIntersecting: true }, + ]); + await fixture.whenStable(); + + expect(tocButtons().map((b) => b.getAttribute('aria-current'))).toEqual([null, 'location']); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lessons.spec.ts b/src/app/thoughts-content/lessons/lessons.spec.ts new file mode 100644 index 0000000..ee46750 --- /dev/null +++ b/src/app/thoughts-content/lessons/lessons.spec.ts @@ -0,0 +1,17 @@ +import { TestBed } from '@angular/core/testing'; +import { LESSON_PAGES } from './lessons'; + +describe('every lesson page', () => { + it.each(Object.keys(LESSON_PAGES))('%s has an "On this page" nav over its five sections', async (slug) => { + const page = await LESSON_PAGES[slug](); + const fixture = TestBed.createComponent(page); + await fixture.whenStable(); + + const entries = [ + ...(fixture.nativeElement as HTMLElement).querySelectorAll('nav[aria-label="On this page"] button'), + ].map((button) => button.textContent?.trim()); + expect(entries).toEqual( + expect.arrayContaining(['Simple', 'Intermediate', 'Expert', 'Pitfalls', 'Interview questions']), + ); + }); +}); diff --git a/src/app/thoughts-content/lessons/scroll-spy.spec.ts b/src/app/thoughts-content/lessons/scroll-spy.spec.ts new file mode 100644 index 0000000..07bc6d4 --- /dev/null +++ b/src/app/thoughts-content/lessons/scroll-spy.spec.ts @@ -0,0 +1,76 @@ +import { Component, viewChild } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { FakeIntersectionObserver } from '../../../test/fake-intersection-observer'; +import { ScrollSpy } from './scroll-spy'; + +@Component({ + imports: [ScrollSpy], + template: ` +
+
1
+
2
+
3
+
+ `, +}) +class Host { + readonly spy = viewChild.required(ScrollSpy); +} + +describe('ScrollSpy', () => { + let fixture: ComponentFixture; + let spy: ScrollSpy; + const section = (id: string) => fixture.nativeElement.querySelector(`#${id}`) as HTMLElement; + + async function render() { + fixture = TestBed.createComponent(Host); + await fixture.whenStable(); + spy = fixture.componentInstance.spy(); + for (const id of ['one', 'two', 'three']) spy.register(section(id)); + } + + beforeEach(() => FakeIntersectionObserver.install()); + afterEach(() => FakeIntersectionObserver.uninstall()); + + it('observes every registered element', async () => { + await render(); + expect(FakeIntersectionObserver.latest().observed).toEqual([section('one'), section('two'), section('three')]); + }); + + it('marks the first intersecting element, in registration order, as active', async () => { + await render(); + const observer = FakeIntersectionObserver.latest(); + + observer.report([ + { target: section('three'), isIntersecting: true }, + { target: section('two'), isIntersecting: true }, + ]); + expect(spy.activeId()).toBe('two'); + + observer.report([{ target: section('two'), isIntersecting: false }]); + expect(spy.activeId()).toBe('three'); + }); + + it('keeps the last active id while nothing is intersecting, e.g. mid-way through a long section', async () => { + await render(); + const observer = FakeIntersectionObserver.latest(); + + observer.report([{ target: section('two'), isIntersecting: true }]); + observer.report([{ target: section('two'), isIntersecting: false }]); + expect(spy.activeId()).toBe('two'); + }); + + it('disconnects its observer when destroyed', async () => { + await render(); + fixture.destroy(); + expect(FakeIntersectionObserver.latest().disconnected).toBe(true); + }); + + it('stays inert where IntersectionObserver does not exist', async () => { + FakeIntersectionObserver.uninstall(); + vi.stubGlobal('IntersectionObserver', undefined); + await render(); + expect(spy.activeId()).toBeNull(); + vi.unstubAllGlobals(); + }); +}); diff --git a/src/test/fake-intersection-observer.ts b/src/test/fake-intersection-observer.ts new file mode 100644 index 0000000..1f55f2e --- /dev/null +++ b/src/test/fake-intersection-observer.ts @@ -0,0 +1,52 @@ +/** + * jsdom has no IntersectionObserver. This stand-in records what it was asked + * to observe and lets a spec decide what is "in view". + */ +export class FakeIntersectionObserver { + private static instances: FakeIntersectionObserver[] = []; + private static original: typeof IntersectionObserver | undefined; + + readonly observed: Element[] = []; + disconnected = false; + + constructor( + private readonly callback: IntersectionObserverCallback, + readonly options?: IntersectionObserverInit, + ) { + FakeIntersectionObserver.instances.push(this); + } + + static install(): void { + FakeIntersectionObserver.instances = []; + FakeIntersectionObserver.original = globalThis.IntersectionObserver; + globalThis.IntersectionObserver = FakeIntersectionObserver as unknown as typeof IntersectionObserver; + } + + static uninstall(): void { + globalThis.IntersectionObserver = FakeIntersectionObserver.original as typeof IntersectionObserver; + } + + static latest(): FakeIntersectionObserver { + const latest = FakeIntersectionObserver.instances.at(-1); + if (!latest) throw new Error('No IntersectionObserver was created'); + return latest; + } + + observe(element: Element): void { + this.observed.push(element); + } + + unobserve(): void {} + + disconnect(): void { + this.disconnected = true; + } + + takeRecords(): IntersectionObserverEntry[] { + return []; + } + + report(entries: { target: Element; isIntersecting: boolean }[]): void { + this.callback(entries as IntersectionObserverEntry[], this as unknown as IntersectionObserver); + } +} From 0707817dc6de46b9d1f503293c5c804fd74f4250 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:19:48 -0500 Subject: [PATCH 2/4] Add an On this page nav to every lesson LessonSection matches each h2 in a lesson, gives it an id from its text and registers it with ScrollSpy, which the lesson component takes as a host directive. ScrollSpy creates its IntersectionObserver in afterNextRender, so prerender never touches it, and highlights the section in view. The lesson spec's scrollIntoView mock needed a type. --- .../lessons/lesson-01-structure.ts | 3 +- .../lessons/lesson-02-components.ts | 3 +- .../lessons/lesson-03-templates.ts | 3 +- .../lessons/lesson-04-signals.ts | 3 +- .../thoughts-content/lessons/lesson-05-di.ts | 3 +- .../lessons/lesson-06-rxjs.ts | 3 +- .../lessons/lesson-07-routing.ts | 3 +- .../lessons/lesson-08-forms.ts | 3 +- .../lessons/lesson-09-change-detection.ts | 2 + .../lessons/lesson-section.ts | 50 +++++++++++++ .../thoughts-content/lessons/lesson.spec.ts | 4 +- src/app/thoughts-content/lessons/lesson.ts | 73 ++++++++++++++++++- .../thoughts-content/lessons/scroll-spy.ts | 55 ++++++++++++++ 13 files changed, 197 insertions(+), 11 deletions(-) create mode 100644 src/app/thoughts-content/lessons/lesson-section.ts create mode 100644 src/app/thoughts-content/lessons/scroll-spy.ts diff --git a/src/app/thoughts-content/lessons/lesson-01-structure.ts b/src/app/thoughts-content/lessons/lesson-01-structure.ts index 12d842c..b65c561 100644 --- a/src/app/thoughts-content/lessons/lesson-01-structure.ts +++ b/src/app/thoughts-content/lessons/lesson-01-structure.ts @@ -2,6 +2,7 @@ import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/c import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; export type Layer = 'shell' | 'shared' | 'feature' | 'other-feature'; @@ -53,7 +54,7 @@ const LAYER_LABELS: Record = { @Component({ selector: 'app-lesson-01-structure', changeDetection: ChangeDetectionStrategy.OnPush, - imports: [Lesson, LessonDemo, CodeBlock, InterviewQuestions], + imports: [Lesson,LessonSection, LessonDemo, CodeBlock, InterviewQuestions], template: ` diff --git a/src/app/thoughts-content/lessons/lesson-02-components.ts b/src/app/thoughts-content/lessons/lesson-02-components.ts index 6ba84dd..1b1a21c 100644 --- a/src/app/thoughts-content/lessons/lesson-02-components.ts +++ b/src/app/thoughts-content/lessons/lesson-02-components.ts @@ -3,6 +3,7 @@ import { Callout } from './callout'; import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; type Tone = 'info' | 'warn'; @@ -72,7 +73,7 @@ export class DemoBadge { @Component({ selector: 'app-lesson-02-components', changeDetection: ChangeDetectionStrategy.OnPush, - imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions, DemoBadge], + imports: [Lesson,LessonSection, LessonDemo, CodeBlock, Callout, InterviewQuestions, DemoBadge], template: `

Simple

diff --git a/src/app/thoughts-content/lessons/lesson-03-templates.ts b/src/app/thoughts-content/lessons/lesson-03-templates.ts index a78310f..f34954f 100644 --- a/src/app/thoughts-content/lessons/lesson-03-templates.ts +++ b/src/app/thoughts-content/lessons/lesson-03-templates.ts @@ -3,6 +3,7 @@ import { Callout } from './callout'; import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; const STARTING_TAGS = ['signals', 'pipes', 'control-flow']; @@ -10,7 +11,7 @@ const STARTING_TAGS = ['signals', 'pipes', 'control-flow']; @Component({ selector: 'app-lesson-03-templates', changeDetection: ChangeDetectionStrategy.OnPush, - imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + imports: [Lesson,LessonSection, LessonDemo, CodeBlock, Callout, InterviewQuestions], template: `

Simple

diff --git a/src/app/thoughts-content/lessons/lesson-04-signals.ts b/src/app/thoughts-content/lessons/lesson-04-signals.ts index 90cfeb4..ca0c2d6 100644 --- a/src/app/thoughts-content/lessons/lesson-04-signals.ts +++ b/src/app/thoughts-content/lessons/lesson-04-signals.ts @@ -3,6 +3,7 @@ import { Callout } from './callout'; import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; const UNIT_PRICE = 12; @@ -16,7 +17,7 @@ const SHIPPING: Record = { @Component({ selector: 'app-lesson-04-signals', changeDetection: ChangeDetectionStrategy.OnPush, - imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + imports: [Lesson,LessonSection, LessonDemo, CodeBlock, Callout, InterviewQuestions], template: `

Simple

diff --git a/src/app/thoughts-content/lessons/lesson-05-di.ts b/src/app/thoughts-content/lessons/lesson-05-di.ts index 88ba827..1a3ce84 100644 --- a/src/app/thoughts-content/lessons/lesson-05-di.ts +++ b/src/app/thoughts-content/lessons/lesson-05-di.ts @@ -3,6 +3,7 @@ import { Callout } from './callout'; import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; /** @@ -77,7 +78,7 @@ export class TallyButton { @Component({ selector: 'app-lesson-05-di', changeDetection: ChangeDetectionStrategy.OnPush, - imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions, TallyScope, TallyButton], + imports: [Lesson,LessonSection, LessonDemo, CodeBlock, Callout, InterviewQuestions, TallyScope, TallyButton], providers: [TallyNumbering], template: ` diff --git a/src/app/thoughts-content/lessons/lesson-06-rxjs.ts b/src/app/thoughts-content/lessons/lesson-06-rxjs.ts index 1d8bd4c..3fe238d 100644 --- a/src/app/thoughts-content/lessons/lesson-06-rxjs.ts +++ b/src/app/thoughts-content/lessons/lesson-06-rxjs.ts @@ -6,6 +6,7 @@ import { Callout } from './callout'; import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; import { searchAsYouType, SearchStrategy } from './search-race'; @@ -30,7 +31,7 @@ function slowSearch(query: string): Observable { @Component({ selector: 'app-lesson-06-rxjs', changeDetection: ChangeDetectionStrategy.OnPush, - imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + imports: [Lesson,LessonSection, LessonDemo, CodeBlock, Callout, InterviewQuestions], template: `

Simple

diff --git a/src/app/thoughts-content/lessons/lesson-07-routing.ts b/src/app/thoughts-content/lessons/lesson-07-routing.ts index 0143c80..f91dd12 100644 --- a/src/app/thoughts-content/lessons/lesson-07-routing.ts +++ b/src/app/thoughts-content/lessons/lesson-07-routing.ts @@ -5,6 +5,7 @@ import { Callout } from './callout'; import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; import { firstMatch } from './route-match'; @@ -14,7 +15,7 @@ const entries = (record: Record) => @Component({ selector: 'app-lesson-07-routing', changeDetection: ChangeDetectionStrategy.OnPush, - imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + imports: [Lesson,LessonSection, LessonDemo, CodeBlock, Callout, InterviewQuestions], template: `

Simple

diff --git a/src/app/thoughts-content/lessons/lesson-08-forms.ts b/src/app/thoughts-content/lessons/lesson-08-forms.ts index 1914208..8ea11fb 100644 --- a/src/app/thoughts-content/lessons/lesson-08-forms.ts +++ b/src/app/thoughts-content/lessons/lesson-08-forms.ts @@ -4,6 +4,7 @@ import { Callout } from './callout'; import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; /** @@ -19,7 +20,7 @@ const matchingPasswords: ValidatorFn = (group): ValidationErrors | null => { @Component({ selector: 'app-lesson-08-forms', changeDetection: ChangeDetectionStrategy.OnPush, - imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions, ReactiveFormsModule], + imports: [Lesson,LessonSection, LessonDemo, CodeBlock, Callout, InterviewQuestions, ReactiveFormsModule], template: `

Simple

diff --git a/src/app/thoughts-content/lessons/lesson-09-change-detection.ts b/src/app/thoughts-content/lessons/lesson-09-change-detection.ts index 73d5d4d..14569e3 100644 --- a/src/app/thoughts-content/lessons/lesson-09-change-detection.ts +++ b/src/app/thoughts-content/lessons/lesson-09-change-detection.ts @@ -10,6 +10,7 @@ import { Callout } from './callout'; import { CodeBlock } from './code-block'; import { InterviewQuestions } from './interview-questions'; import { Lesson } from './lesson'; +import { LessonSection } from './lesson-section'; import { LessonDemo } from './lesson-demo'; interface Profile { @@ -63,6 +64,7 @@ export class OnPushProfileCard { changeDetection: ChangeDetectionStrategy.OnPush, imports: [ Lesson, + LessonSection, LessonDemo, CodeBlock, Callout, diff --git a/src/app/thoughts-content/lessons/lesson-section.ts b/src/app/thoughts-content/lessons/lesson-section.ts new file mode 100644 index 0000000..9e4fc0e --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-section.ts @@ -0,0 +1,50 @@ +import { Directive, ElementRef, inject } from '@angular/core'; +import { ScrollSpy } from './scroll-spy'; + +/** + * [ng-10 directives] A directive whose selector is a plain element, `h2`. + * Every h2 in a template that imports this gets it, with no attribute to + * remember. Angular's own NgForm does the same with `form`. The selector only + * applies in templates that import the directive, so it can't leak site-wide. + * + * The id comes from the heading's text, so it's stable between the server + * render and the browser, and readable in a URL. + */ +@Directive({ + selector: 'h2', + host: { '[id]': 'id', tabindex: '-1' }, +}) +export class LessonSection { + private readonly host = inject>(ElementRef); + + // Getters, not fields: a directive is created when its element opens, + // before the heading's text node exists, so the constructor sees ''. + // Host bindings and the lesson nav read these later, once it does. + get label(): string { + return this.host.nativeElement.textContent?.trim() ?? ''; + } + + get id(): string { + return this.label + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, ''); + } + + constructor() { + // Element injectors follow the template, so a heading projected into + // finds the ScrollSpy on that host. Optional: an h2 outside a + // lesson still gets its id. + inject(ScrollSpy, { optional: true })?.register(this.host.nativeElement); + } + + scrollIntoView(): void { + // Browsers don't apply prefers-reduced-motion to smooth scrolling for us. + const reduceMotion = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches; + this.host.nativeElement.scrollIntoView({ + behavior: reduceMotion ? 'auto' : 'smooth', + block: 'start', + }); + this.host.nativeElement.focus({ preventScroll: true }); + } +} diff --git a/src/app/thoughts-content/lessons/lesson.spec.ts b/src/app/thoughts-content/lessons/lesson.spec.ts index bf6d0bf..9d07a44 100644 --- a/src/app/thoughts-content/lessons/lesson.spec.ts +++ b/src/app/thoughts-content/lessons/lesson.spec.ts @@ -24,13 +24,13 @@ class Host {} describe('Lesson', () => { let fixture: ComponentFixture; let el: HTMLElement; - let scrollIntoView: ReturnType; + let scrollIntoView: ReturnType>; const tocButtons = () => [...el.querySelectorAll('nav[aria-label="On this page"] button')]; beforeEach(async () => { FakeIntersectionObserver.install(); - scrollIntoView = vi.fn(); + scrollIntoView = vi.fn(); Element.prototype.scrollIntoView = scrollIntoView; fixture = TestBed.createComponent(Host); await fixture.whenStable(); diff --git a/src/app/thoughts-content/lessons/lesson.ts b/src/app/thoughts-content/lessons/lesson.ts index 6c0b6b5..22f059e 100644 --- a/src/app/thoughts-content/lessons/lesson.ts +++ b/src/app/thoughts-content/lessons/lesson.ts @@ -1,4 +1,13 @@ -import { ChangeDetectionStrategy, Component, input, ViewEncapsulation } from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + contentChildren, + inject, + input, + ViewEncapsulation, +} from '@angular/core'; +import { LessonSection } from './lesson-section'; +import { ScrollSpy } from './scroll-spy'; /** * [ng-02 components] The shared typography for every lesson page. @@ -15,9 +24,30 @@ import { ChangeDetectionStrategy, Component, input, ViewEncapsulation } from '@a selector: 'app-lesson', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, + // [ng-10 directives] Composition instead of inheritance: the lesson gets + // ScrollSpy's behaviour without extending a class or anyone writing + // appScrollSpy on . The headings inside find it through DI. + hostDirectives: [ScrollSpy], template: `

Angular guide · Part {{ part() }}

+ @if (sections().length) { + + }
`, @@ -34,10 +64,47 @@ import { ChangeDetectionStrategy, Component, input, ViewEncapsulation } from '@a letter-spacing: 0.06em; color: var(--accent-color, #007aff); } + .lesson .lesson-toc { + position: sticky; + top: 0; + z-index: 1; + padding: 6px 0; + background: var(--window-bg, rgba(30, 30, 30, 0.95)); + } + .lesson .lesson-toc ul { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; + } + .lesson .lesson-toc button { + font: inherit; + font-size: 12px; + padding: 2px 10px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.2)); + border-radius: 12px; + background: none; + color: var(--text-primary, #fff); + cursor: pointer; + } + .lesson .lesson-toc button[aria-current='location'] { + border-color: var(--accent-color, #007aff); + background: var(--accent-color, #007aff); + color: #fff; + } + .lesson .lesson-toc button:focus-visible, + .lesson h2:focus-visible { + outline: 2px solid var(--accent-color, #007aff); + outline-offset: 2px; + } .lesson h2 { margin: 28px 0 8px; font-size: 17px; color: var(--text-primary, #fff); + /* Leaves room for the sticky nav when a section is jumped to. */ + scroll-margin-top: 48px; } .lesson code { font-family: var(--font-mono, ui-monospace, monospace); @@ -61,4 +128,8 @@ import { ChangeDetectionStrategy, Component, input, ViewEncapsulation } from '@a export class Lesson { /** Two-digit part number, e.g. "02". */ readonly part = input.required(); + + protected readonly spy = inject(ScrollSpy); + // descendants: true, because a lesson may wrap a heading in another element. + protected readonly sections = contentChildren(LessonSection, { descendants: true }); } diff --git a/src/app/thoughts-content/lessons/scroll-spy.ts b/src/app/thoughts-content/lessons/scroll-spy.ts new file mode 100644 index 0000000..1b77a4f --- /dev/null +++ b/src/app/thoughts-content/lessons/scroll-spy.ts @@ -0,0 +1,55 @@ +import { afterNextRender, DestroyRef, Directive, inject, signal } from '@angular/core'; + +/** + * [ng-10 directives] An attribute directive: behaviour with no template of + * its own. It tracks which of a set of elements is in view and exposes that + * element's id as a signal. + * + * Elements register themselves (see LessonSection) instead of this directive + * querying the DOM for them. That keeps it ignorant of what a "section" is, + * the same way NgForm doesn't search for inputs: each NgModel registers with + * the form it finds through DI. + */ +@Directive({ + selector: '[appScrollSpy]', + exportAs: 'scrollSpy', +}) +export class ScrollSpy { + private readonly active = signal(null); + readonly activeId = this.active.asReadonly(); + + private readonly elements: HTMLElement[] = []; + private readonly intersecting = new Set(); + private observer?: IntersectionObserver; + + constructor() { + // afterNextRender never runs on the server, where there's no viewport to + // observe. Creating the observer in the constructor would crash prerender. + afterNextRender(() => { + if (typeof IntersectionObserver === 'undefined') return; + // The trigger line is the top 30% of the viewport: a section becomes + // current once its heading scrolls up into that band. + this.observer = new IntersectionObserver((entries) => this.update(entries), { + rootMargin: '0px 0px -70% 0px', + }); + for (const element of this.elements) this.observer.observe(element); + }); + inject(DestroyRef).onDestroy(() => this.observer?.disconnect()); + } + + register(element: HTMLElement): void { + this.elements.push(element); + this.observer?.observe(element); + } + + private update(entries: IntersectionObserverEntry[]): void { + for (const entry of entries) { + if (entry.isIntersecting) this.intersecting.add(entry.target); + else this.intersecting.delete(entry.target); + } + // Between headings nothing intersects; keep the last one rather than + // clearing, because the reader is still inside that section. + const first = this.elements.find((element) => this.intersecting.has(element)); + if (first) this.active.set(first.id); + } +} From 57bfabbe500ffc980bfa5660b0f8bbeca985cf5f Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:19:48 -0500 Subject: [PATCH 3/4] Write lesson 10 with structural and host directive demos The tag page spec assumed every guide title starts "Angular 0", which stopped being true at lesson 10; it now matches two digits. --- src/app/app.routes.spec.ts | 2 +- .../lessons/lesson-10-directives.ts | 307 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 1 + src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 5 files changed, 321 insertions(+), 1 deletion(-) create mode 100644 src/app/thoughts-content/lessons/lesson-10-directives.ts diff --git a/src/app/app.routes.spec.ts b/src/app/app.routes.spec.ts index d049680..41a7474 100644 --- a/src/app/app.routes.spec.ts +++ b/src/app/app.routes.spec.ts @@ -40,6 +40,6 @@ describe('app routes', () => { expect(harness.routeDebugElement?.componentInstance).toBeInstanceOf(ThoughtsListComponent); expect(titles.length).toBeGreaterThan(0); - expect(titles.every((title) => title.includes('Angular 0'))).toBe(true); + expect(titles.every((title) => /Angular \d{2}:/.test(title))).toBe(true); }); }); diff --git a/src/app/thoughts-content/lessons/lesson-10-directives.ts b/src/app/thoughts-content/lessons/lesson-10-directives.ts new file mode 100644 index 0000000..012c1a8 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-10-directives.ts @@ -0,0 +1,307 @@ +import { + ChangeDetectionStrategy, + Component, + Directive, + effect, + inject, + input, + signal, + TemplateRef, + ViewContainerRef, +} from '@angular/core'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; +import { LessonSection } from './lesson-section'; + +// [ng-10 directives] A structural directive: it decides whether its template +// exists at all. The * in *appDemoUnless is sugar for wrapping the element in +// an , which is what TemplateRef points at. +@Directive({ selector: '[appDemoUnless]' }) +export class DemoUnless { + private readonly template = inject(TemplateRef); + private readonly container = inject(ViewContainerRef); + readonly appDemoUnless = input.required(); + + constructor() { + effect(() => { + this.container.clear(); + if (!this.appDemoUnless()) this.container.createEmbeddedView(this.template); + }); + } +} + +// [ng-10 directives] An attribute directive: no template, just behaviour on +// its host. The `host` metadata replaces @HostBinding and @HostListener. +@Directive({ + selector: '[appDemoHighlight]', + host: { '[style.background-color]': 'appDemoHighlight()' }, +}) +export class DemoHighlight { + readonly appDemoHighlight = input(''); +} + +// [ng-10 directives] The same directive composed into a component. The +// directive's input is exposed under a friendlier name; inputs a host +// directive doesn't list stay private to the component. +@Component({ + selector: 'app-demo-chip', + changeDetection: ChangeDetectionStrategy.OnPush, + hostDirectives: [{ directive: DemoHighlight, inputs: ['appDemoHighlight: color'] }], + template: ``, + styles: ` + :host { + display: inline-block; + padding: 2px 10px; + border-radius: 12px; + background: #e8e8ed; + color: #111; + } + `, +}) +export class DemoChip {} + +@Component({ + selector: 'app-lesson-10-directives', + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ + Lesson, + LessonSection, + LessonDemo, + CodeBlock, + Callout, + InterviewQuestions, + DemoUnless, + DemoChip, + ], + template: ` + +

Simple

+

+ A directive adds behaviour to an element that already exists. A component + is a directive that also brings a template. There are two other kinds: +

+
    +
  • + Attribute directives change how an element looks or behaves. Built-in + examples are NgClass and RouterLink. +
  • +
  • + Structural directives add and remove elements. *ngIf and + *ngFor were the famous ones, and the built-in @if and + @for blocks have mostly replaced them. +
  • +
+

+ The nav at the top of this page comes from two directives I wrote for this lesson. + LessonSection gives every heading an id and registers it. + ScrollSpy watches the registered headings with an + IntersectionObserver and highlights the section you're reading. Scroll, and + watch the nav follow. +

+ + +

Intermediate

+

+ Structural directives inject a TemplateRef (what to render) + and a ViewContainerRef (where to render it). The * is sugar: + *appDemoUnless="hidden()" wraps the element in an + <ng-template> and binds the expression to an input named after the + selector. +

+ +
+ +
+

+ I exist only while the condition is false. When it's true, I'm not hidden with CSS; I'm + gone from the DOM. +

+
+ + +

Expert

+

+ Composition with hostDirectives. A component can take on a directive's + behaviour without anyone writing its attribute, and without inheritance. The lesson + component on this page does exactly that with ScrollSpy. You choose which of + the directive's inputs and outputs to expose, and you can rename them. +

+ +
+ + + angular +
+
+ +

+ Directives talking through DI. Each heading finds the + ScrollSpy by injecting it. Element injectors follow the template, so a heading + projected into <app-lesson> resolves the one on that host. + NgModel finds its NgForm and RouterLinkActive finds + its links the same way. It beats the parent querying the DOM: the child knows what it is, + and the parent stays generic. +

+ + +

+ LessonSection's selector is just h2. Every h2 in a template that + imports it gets the directive, no attribute needed. NgForm does the same with + form, which is why a plain form in a template-driven app is already an + NgForm. It's powerful, and it only applies where the directive is imported, + but it's easy to surprise someone with. +

+
+ +

Pitfalls

+ +

+ Reading the DOM in a constructor. A directive is created when its element + opens, before its children exist. My first draft of LessonSection read the + heading's text in a field initialiser, which runs before the text node exists, so every id + would have come out empty. Read it later: in a getter that a binding calls, or in + afterNextRender. +

+
+ +

+ Browser APIs during SSR. IntersectionObserver, + window and matchMedia don't exist on the server. Code that needs + them belongs in afterNextRender, which never runs there. +

+
+ +

+ Observers and listeners that outlive the element. Disconnect them in + DestroyRef.onDestroy. Otherwise every visit to a page leaks one more + observer. +

+
+ +

+ One structural directive per element. *ngIf and + *ngFor on the same element is an error. Wrap one in an + <ng-container>, or use @if and @for. +

+
+ +

Interview questions

+ +
+ `, +}) +export class Lesson10Directives { + protected readonly hidden = signal(false); + protected readonly chipColor = signal(''); + + protected readonly snippets = { + section: `@Directive({ + selector: 'h2', // every h2 where this is imported + host: { '[id]': 'id', tabindex: '-1' }, +}) +export class LessonSection { + private readonly host = inject>(ElementRef); + + get label() { return this.host.nativeElement.textContent?.trim() ?? ''; } + get id() { return this.label.toLowerCase().replace(/[^a-z0-9]+/g, '-'); } + + constructor() { + inject(ScrollSpy, { optional: true })?.register(this.host.nativeElement); + } +}`, + unless: `@Directive({ selector: '[appDemoUnless]' }) +export class DemoUnless { + private readonly template = inject(TemplateRef); + private readonly container = inject(ViewContainerRef); + readonly appDemoUnless = input.required(); + + constructor() { + effect(() => { + this.container.clear(); + if (!this.appDemoUnless()) this.container.createEmbeddedView(this.template); + }); + } +} + +

…

+ +

…

`, + hostDirectives: `@Directive({ + selector: '[appDemoHighlight]', + host: { '[style.background-color]': 'appDemoHighlight()' }, +}) +export class DemoHighlight { + readonly appDemoHighlight = input(''); +} + +@Component({ + selector: 'app-demo-chip', + hostDirectives: [{ directive: DemoHighlight, inputs: ['appDemoHighlight: color'] }], + template: '', +}) +export class DemoChip {} + +angular`, + spy: `@Directive({ selector: '[appScrollSpy]', exportAs: 'scrollSpy' }) +export class ScrollSpy { + private readonly active = signal(null); + readonly activeId = this.active.asReadonly(); + private observer?: IntersectionObserver; + + constructor() { + afterNextRender(() => { // browser only + this.observer = new IntersectionObserver( + (entries) => this.update(entries), + { rootMargin: '0px 0px -70% 0px' }, // top 30% of the viewport + ); + for (const element of this.elements) this.observer.observe(element); + }); + inject(DestroyRef).onDestroy(() => this.observer?.disconnect()); + } +} + +@Component({ selector: 'app-lesson', hostDirectives: [ScrollSpy], ... })`, + }; + + protected readonly interview = [ + { + q: 'What kinds of directives are there?', + a: 'Components, which are directives with a template; attribute directives, which change the appearance or behaviour of their host element; and structural directives, which add or remove DOM by rendering a TemplateRef into a ViewContainerRef. Since Angular 17 the built-in @if, @for and @switch blocks cover most structural needs without a directive.', + }, + { + q: 'What does the * in *ngIf do?', + a: 'It is shorthand. The element is wrapped in an , and the expression is bound to an input named after the directive selector. Microsyntax like "let item of items; trackBy: f" maps to more inputs, such as ngForOf and ngForTrackBy, and to template context variables.', + }, + { + q: 'What are host directives and why use them?', + a: 'hostDirectives on a component or directive applies other standalone directives to its host element, as if their attributes were written there. You pick which inputs and outputs to expose and can alias them. It is composition instead of inheritance: behaviour like focus handling, tooltips or scroll tracking can be shared without base classes, and consumers cannot forget to add it.', + }, + { + q: 'How do parent and child directives communicate?', + a: 'Through DI. A child injects the parent directive, optionally, from its element injector and registers itself, the way NgModel registers with NgForm or my headings register with ScrollSpy. The parent can also use contentChildren to query children. Registration keeps the parent generic, and queries are good when the parent needs an ordered list of children to render.', + }, + { + q: '@HostBinding and @HostListener vs the host property?', + a: 'Both do the same job. The Angular style guide now prefers the host property in the decorator metadata, because all host bindings sit in one place and work cleanly with signals. The decorators still work, and plenty of existing code uses them.', + }, + { + q: 'Where should DOM work in a directive happen?', + a: 'Not in the constructor, because children do not exist yet and on the server there is no browser DOM. Use afterNextRender or afterEveryRender for browser-only work like measuring or observers, and DestroyRef to clean up. Bindings in the host metadata are the safe way to write to the host element, since Angular applies them on the server too.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index 8bceb26..3d4c894 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -21,4 +21,5 @@ export const LESSON_PAGES: Record Promise>> = { 'angular-08-forms': () => import('./lesson-08-forms').then((m) => m.Lesson08Forms), 'angular-09-change-detection': () => import('./lesson-09-change-detection').then((m) => m.Lesson09ChangeDetection), + 'angular-10-directives': () => import('./lesson-10-directives').then((m) => m.Lesson10Directives), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index a75055c..07944e0 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -271,4 +271,7 @@ All three are fixed now. Send stays enabled; pressing it shows every problem and 'angular-09-change-detection': `Until this lesson, none of the 35 components on this site set a change detection strategy, so every one of them was checked on every pass. Before switching them all to OnPush, I went through each looking for state that changes outside signals and template events, since that's the state OnPush silently stops rendering. There was none, which says more about the earlier lessons moving everything to signals than about luck. The closest call is the contact form's reset, which only shows up because a signal write sits next to it. A test in architecture.spec.ts now fails on any component that doesn't choose a strategy. The demo below sets an Eager child next to an OnPush one and passes both the same object, so you can watch mutation leave one of them behind.`, + 'angular-10-directives': `By lesson nine the pages were long enough that I kept losing my place in them, so every lesson now has an "On this page" nav that sticks to the top and highlights the section you're in. It comes from two small directives, and they cover most of what directives are for. + +One gives every heading an id and registers it. The other watches those headings and reports which one is in view. The lesson component picks that up as a host directive rather than anyone remembering to add an attribute. The demos below cover the parts the nav didn't need: a structural directive, and an input renamed through hostDirectives.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index 22fd623..bcf5c24 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -269,4 +269,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'change-detection', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-10-directives', + title: 'Angular 10: Directives', + date: '2026-11-21', + summary: + 'Attribute and structural directives, element selectors, host directives, and directives that find each other through DI. Built while adding an "On this page" nav that follows you down every lesson.', + tags: ['angular-guide', 'directives', 'angular'], + relatedApp: 'readme', + }, ]; From 9e16af4a7da6d7451e70e2d6925904fe6edb08f3 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:19:48 -0500 Subject: [PATCH 4/4] Bump to 1.4.9 with the lesson 10 changelog entry --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f15b235..2241f50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to this project will be documented in this file. +## 2026-11-21 - version 1.4.9 + +- **Every lesson has an "On this page" nav.** It sticks to the top while you read, jumps to a section (moving focus to its heading), and highlights the section in view with `aria-current="location"`. Smooth scrolling switches off under `prefers-reduced-motion`. The lessons had grown long enough that I kept losing my place in them +- **Two directives build it.** `LessonSection` matches every `h2` in a lesson, gives it an id from its text and registers it with `ScrollSpy`, which watches the registered headings with an `IntersectionObserver` created only in the browser. The lesson component takes `ScrollSpy` as a host directive, so no lesson has to remember an attribute. The nav and the heading ids are both in the prerendered HTML +- **Angular guide, lesson 10: directives** (`/thoughts/angular-10-directives`). The live demos are a structural directive built on `TemplateRef` and `ViewContainerRef`, and an attribute directive composed into a component with `hostDirectives` and a renamed input. The lesson walks through the nav's own code +- **Initial bundle 392.64 → 394.56 kB.** All the new code is lazy, but this is the first use of `contentChildren`, `hostDirectives` and `afterNextRender`, and their runtime lives in the shared `@angular/core` chunk + ## 2026-11-21 - version 1.4.8 - **Every component is OnPush.** None of the 35 components set a change detection strategy, so every one was checked on every pass. Each now uses `ChangeDetectionStrategy.OnPush`. Before switching, I audited each component for state that changes outside signals and template events, the kind OnPush stops rendering, and found none. The contact form's reset after sending is the closest call, and it now carries a comment saying why it still renders diff --git a/package-lock.json b/package-lock.json index 93ce887..e36aa50 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.8", + "version": "1.4.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.8", + "version": "1.4.9", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index b1d14a4..50c0c21 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.8", + "version": "1.4.9", "scripts": { "ng": "ng", "start": "ng serve",