From cdb634e8aa1cce92f79756ea60f10cbb3bd16785 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:13:45 -0500 Subject: [PATCH 1/5] Add failing specs for tag pages, a wildcard route and lesson 07 --- src/app/app.routes.server.spec.ts | 12 ++++ src/app/app.routes.spec.ts | 45 ++++++++++++++ src/app/shared/seo.service.spec.ts | 9 +++ .../lessons/lesson-07-routing.spec.ts | 59 +++++++++++++++++++ .../lessons/route-match.spec.ts | 40 +++++++++++++ .../thoughts-content/thought-detail.spec.ts | 9 ++- .../thoughts-content/thoughts-list.spec.ts | 35 +++++++++-- 7 files changed, 202 insertions(+), 7 deletions(-) create mode 100644 src/app/app.routes.spec.ts create mode 100644 src/app/thoughts-content/lessons/lesson-07-routing.spec.ts create mode 100644 src/app/thoughts-content/lessons/route-match.spec.ts diff --git a/src/app/app.routes.server.spec.ts b/src/app/app.routes.server.spec.ts index a04c1c2..3002f35 100644 --- a/src/app/app.routes.server.spec.ts +++ b/src/app/app.routes.server.spec.ts @@ -22,6 +22,18 @@ describe('serverRoutes', () => { expect(slugs).toEqual(expected); }); + it('prerenders a page for every tag', async () => { + const route = serverRoutes.find((r) => r.path === 'thoughts/tag/:tag'); + expect(route?.renderMode).toBe(RenderMode.Prerender); + + const params = await ( + route as unknown as { getPrerenderParams: () => Promise<{ tag: string }[]> } + ).getPrerenderParams(); + const expected = [...new Set(THOUGHTS.flatMap((t) => t.tags))].sort(); + + expect(params.map((p) => p.tag).sort()).toEqual(expected); + }); + it('keeps the catch-all route client-rendered', () => { const route = serverRoutes.find((r) => r.path === '**'); expect(route?.renderMode).toBe(RenderMode.Client); diff --git a/src/app/app.routes.spec.ts b/src/app/app.routes.spec.ts new file mode 100644 index 0000000..d049680 --- /dev/null +++ b/src/app/app.routes.spec.ts @@ -0,0 +1,45 @@ +import { TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { appConfig } from './app.config'; +import { ThoughtDetailComponent } from './thoughts-content/thought-detail'; +import { ThoughtsListComponent } from './thoughts-content/thoughts-list'; + +/** + * The real route table with the real router features from appConfig, so + * these catch a route that's missing, in the wrong order, or relying on a + * router feature that isn't switched on. + */ +async function navigate(url: string) { + TestBed.configureTestingModule({ providers: appConfig.providers }); + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl(url); + await harness.fixture.whenStable(); + return { harness, router: TestBed.inject(Router) }; +} + +describe('app routes', () => { + it('sends an unknown URL to the desktop instead of failing the navigation', async () => { + const { router } = await navigate('/no-such-page'); + expect(router.url).toBe('/'); + }); + + it('binds :slug straight to the reader input', async () => { + const { harness } = await navigate('/thoughts/angular-02-components'); + const reader = harness.routeDebugElement?.componentInstance; + + expect(reader).toBeInstanceOf(ThoughtDetailComponent); + expect(harness.routeNativeElement?.textContent).toContain('Angular 02: Components'); + }); + + it('serves a tag page that lists only that tag', async () => { + const { harness } = await navigate('/thoughts/tag/angular-guide'); + const titles = [...harness.routeNativeElement!.querySelectorAll('.thought-card-title')].map( + (title) => title.textContent ?? '', + ); + + expect(harness.routeDebugElement?.componentInstance).toBeInstanceOf(ThoughtsListComponent); + expect(titles.length).toBeGreaterThan(0); + expect(titles.every((title) => title.includes('Angular 0'))).toBe(true); + }); +}); diff --git a/src/app/shared/seo.service.spec.ts b/src/app/shared/seo.service.spec.ts index 7fb6d2c..d824ec0 100644 --- a/src/app/shared/seo.service.spec.ts +++ b/src/app/shared/seo.service.spec.ts @@ -71,5 +71,14 @@ describe('SeoService', () => { expect(title.getTitle()).toContain(SITE_NAME); expect(doc.querySelector('script[type="application/ld+json"]')).toBeNull(); }); + + it('gives a tag page its own title and canonical URL', () => { + service.setListMeta('signals'); + + expect(title.getTitle()).toContain('signals'); + expect(doc.querySelector('link[rel="canonical"]')?.getAttribute('href')).toMatch( + /\/thoughts\/tag\/signals$/, + ); + }); }); }); diff --git a/src/app/thoughts-content/lessons/lesson-07-routing.spec.ts b/src/app/thoughts-content/lessons/lesson-07-routing.spec.ts new file mode 100644 index 0000000..995541b --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-07-routing.spec.ts @@ -0,0 +1,59 @@ +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 { Lesson07Routing } from './lesson-07-routing'; + +expect.extend(axeMatchers); + +describe('Lesson07Routing', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const text = (selector: string) => el.querySelector(selector)?.textContent ?? ''; + const enterUrl = async (url: string) => { + const input = el.querySelector('#route-url')!; + input.value = url; + input.dispatchEvent(new Event('input')); + await fixture.whenStable(); + }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson07Routing] }).compileComponents(); + fixture = TestBed.createComponent(Lesson07Routing); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-07-routing']).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("matches a URL against this site's real route table and splits it the way the router does", async () => { + await enterUrl('/thoughts/tag/rxjs?ref=dock#top'); + + expect(text('#route-matched')).toContain('thoughts/tag/:tag'); + expect(text('#route-params')).toContain('tag = rxjs'); + expect(text('#route-query')).toContain('ref = dock'); + expect(text('#route-fragment')).toContain('top'); + }); + + it('shows first-match-wins when the wildcard is moved to the front', async () => { + await enterUrl('/thoughts'); + el.querySelector('#wildcard-first')!.click(); + await fixture.whenStable(); + + expect(text('#route-matched')).toContain('**'); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/route-match.spec.ts b/src/app/thoughts-content/lessons/route-match.spec.ts new file mode 100644 index 0000000..e66e60d --- /dev/null +++ b/src/app/thoughts-content/lessons/route-match.spec.ts @@ -0,0 +1,40 @@ +import { Routes } from '@angular/router'; +import { firstMatch } from './route-match'; + +const routes: Routes = [ + { path: '', pathMatch: 'full', children: [] }, + { path: 'thoughts' }, + { path: 'thoughts/tag/:tag' }, + { path: 'thoughts/:slug' }, + { path: '**', redirectTo: '' }, +]; + +describe('firstMatch', () => { + it('matches static segments exactly', () => { + expect(firstMatch(routes, ['thoughts'])).toEqual({ path: 'thoughts', params: {} }); + }); + + it('captures :params from the segments they sit on', () => { + expect(firstMatch(routes, ['thoughts', 'tag', 'rxjs'])).toEqual({ + path: 'thoughts/tag/:tag', + params: { tag: 'rxjs' }, + }); + expect(firstMatch(routes, ['thoughts', 'signals'])).toEqual({ + path: 'thoughts/:slug', + params: { slug: 'signals' }, + }); + }); + + it('matches the empty path only for the root URL', () => { + expect(firstMatch(routes, [])).toEqual({ path: '', params: {} }); + }); + + it('falls through to the wildcard when nothing else fits', () => { + expect(firstMatch(routes, ['nope', 'at', 'all'])).toEqual({ path: '**', params: {} }); + }); + + it('takes the first match in array order, so a wildcard listed first swallows everything', () => { + const wildcardFirst = [routes[4], ...routes.slice(0, 4)]; + expect(firstMatch(wildcardFirst, ['thoughts'])).toEqual({ path: '**', params: {} }); + }); +}); diff --git a/src/app/thoughts-content/thought-detail.spec.ts b/src/app/thoughts-content/thought-detail.spec.ts index f209b0b..aff4253 100644 --- a/src/app/thoughts-content/thought-detail.spec.ts +++ b/src/app/thoughts-content/thought-detail.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { provideRouter, Router } from '@angular/router'; +import { provideRouter, Router, withComponentInputBinding } from '@angular/router'; import { RouterTestingHarness } from '@angular/router/testing'; import { createMemoryStorage } from '../../test/memory-storage'; import { BROWSER_STORAGE } from '../shared/browser-storage'; @@ -18,7 +18,7 @@ async function openThought(slug: string) { provideRouter([ { path: 'thoughts', component: ThoughtsListComponent }, { path: 'thoughts/:slug', component: ThoughtDetailComponent }, - ]), + ], withComponentInputBinding()), // A fresh store per test, so progress marked in one can't leak into the next. { provide: BROWSER_STORAGE, useFactory: () => createMemoryStorage() }, ], @@ -57,6 +57,11 @@ describe('ThoughtDetailComponent', () => { expect(tagTexts).toContain('angular'); }); + it('links each tag to its tag page', () => { + const hrefs = [...el.querySelectorAll('a.thought-tag')].map((a) => a.getAttribute('href')); + expect(hrefs).toContain('/thoughts/tag/signals'); + }); + it('formats the date in UTC, so a YYYY-MM-DD never slips to the day before', () => { // 'signals' is dated 2026-06-15. JS parses that as UTC midnight, so without // UTC formatting any timezone west of UTC renders June 14. diff --git a/src/app/thoughts-content/thoughts-list.spec.ts b/src/app/thoughts-content/thoughts-list.spec.ts index d46c80b..80c16c8 100644 --- a/src/app/thoughts-content/thoughts-list.spec.ts +++ b/src/app/thoughts-content/thoughts-list.spec.ts @@ -1,4 +1,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../test/a11y'; import { provideRouter, Router } from '@angular/router'; import { createMemoryStorage } from '../../test/memory-storage'; import { BROWSER_STORAGE } from '../shared/browser-storage'; @@ -6,6 +8,8 @@ import { ReadingProgressService } from './reading-progress.service'; import { ThoughtsListComponent } from './thoughts-list'; import { ThoughtsService } from './thoughts.service'; +expect.extend(axeMatchers); + describe('ThoughtsListComponent', () => { let fixture: ComponentFixture; let nativeEl: HTMLElement; @@ -48,13 +52,34 @@ describe('ThoughtsListComponent', () => { expect(firstCard.querySelector('.thought-card-preview')?.textContent?.trim()).toBeTruthy(); }); - it('should navigate to /thoughts/:slug when a card is clicked', async () => { - const firstCard = nativeEl.querySelector('.thought-card') as HTMLElement; - firstCard.click(); - fixture.detectChanges(); + it('links each card title to its thought, as a real href', async () => { + const titleLink = nativeEl.querySelector('.thought-card-title a')!; + expect(titleLink.getAttribute('href')).toMatch(/^\/thoughts\/[a-z0-9-]+$/); + + titleLink.click(); await fixture.whenStable(); + expect(router.url).toBe(titleLink.getAttribute('href')); + }); + + it('links each tag pill to its tag page', () => { + const tagLink = nativeEl.querySelector('.thought-card a.thought-tag')!; + expect(tagLink.getAttribute('href')).toBe(`/thoughts/tag/${tagLink.textContent?.trim()}`); + }); + + it('filters to one tag when given one, with a way back to everything', async () => { + fixture.componentRef.setInput('tag', 'angular-guide'); + await fixture.whenStable(); + + const cards = [...nativeEl.querySelectorAll('.thought-card')]; + expect(cards.length).toBe( + TestBed.inject(ThoughtsService).getAll().filter((t) => t.tags.includes('angular-guide')).length, + ); + expect(nativeEl.querySelector('h2')?.textContent).toContain('angular-guide'); + expect(nativeEl.querySelector('a.thoughts-list-all')?.getAttribute('href')).toBe('/thoughts'); + }); - expect(router.url).toMatch(/\/thoughts\/.+/); + it('has no axe violations, including no links nested in a button', async () => { + expect(await axe(nativeEl)).toHaveNoViolations(); }); it('should set SEO metadata for the thoughts list', () => { From 86068a623b8c700bf1a8e5990d250f0ab18b87b4 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:14:52 -0500 Subject: [PATCH 2/5] Bind the reader's slug as a route input --- src/app/app.config.ts | 8 ++++-- .../lessons/lesson-04-signals.ts | 7 ++--- src/app/thoughts-content/thought-detail.ts | 26 ++++++++----------- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/app/app.config.ts b/src/app/app.config.ts index 5352390..169d15b 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -15,7 +15,7 @@ import { provideZonelessChangeDetection, } from '@angular/core'; import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http'; -import { provideRouter } from '@angular/router'; +import { provideRouter, withComponentInputBinding } from '@angular/router'; import { routes } from './app.routes'; import { retryTransientErrors } from './shared/retry-transient-errors.interceptor'; @@ -37,7 +37,11 @@ export const appConfig: ApplicationConfig = { // order on the way back. withInterceptors() takes plain functions; the // class-based HTTP_INTERCEPTORS multi-provider is the legacy form. provideHttpClient(withFetch(), withInterceptors([retryTransientErrors])), - provideRouter(routes), + // [ng-07 routing] withComponentInputBinding(): route params, query params + // and route data arrive as component inputs, so a routed component can + // declare `slug = input.required()` instead of injecting + // ActivatedRoute and bridging an Observable. + provideRouter(routes, withComponentInputBinding()), // SSR hydration: reuse server-rendered DOM instead of re-creating it. // Lesson 12. provideClientHydration(withEventReplay(), withIncrementalHydration()), diff --git a/src/app/thoughts-content/lessons/lesson-04-signals.ts b/src/app/thoughts-content/lessons/lesson-04-signals.ts index 2d2c813..3e09d68 100644 --- a/src/app/thoughts-content/lessons/lesson-04-signals.ts +++ b/src/app/thoughts-content/lessons/lesson-04-signals.ts @@ -87,12 +87,13 @@ const SHIPPING: Record = {

Interop. toSignal() turns an Observable into a signal and - toObservable() goes the other way. The thought reader you're in uses it. It + toObservable() goes the other way. The thought reader you're in used it. It used to read route.snapshot once, and since the router reuses the component when only :slug changes, the series links (Part N of M, below) would have - shown the old lesson. Now the slug is a signal and everything derives from it. + shown the old lesson. Now the slug is a signal and everything derives from it. (Lesson 07 + goes one step further: the router hands the slug over as an input.)

- +

Expert

diff --git a/src/app/thoughts-content/thought-detail.ts b/src/app/thoughts-content/thought-detail.ts index d73a2ad..b379031 100644 --- a/src/app/thoughts-content/thought-detail.ts +++ b/src/app/thoughts-content/thought-detail.ts @@ -1,8 +1,6 @@ import { NgComponentOutlet } from '@angular/common'; -import { Component, computed, effect, ElementRef, inject, resource } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { ActivatedRoute, Router, RouterLink } from '@angular/router'; -import { map } from 'rxjs'; +import { Component, computed, effect, ElementRef, inject, input, resource } from '@angular/core'; +import { Router, RouterLink } from '@angular/router'; import { SeoService } from '../shared/seo.service'; import { LESSON_PAGES } from './lessons/lessons'; import { ReadingProgressService } from './reading-progress.service'; @@ -28,7 +26,7 @@ import { ThoughtsService } from './thoughts.service';

@for (tag of thought.tags; track tag) { - {{ tag }} + {{ tag }} }
{{ thought.content }}
@@ -114,6 +112,7 @@ import { ThoughtsService } from './thoughts.service'; } .thought-tag { + text-decoration: none; font-size: 11px; padding: 3px 10px; border-radius: 12px; @@ -175,7 +174,6 @@ import { ThoughtsService } from './thoughts.service'; `, }) export class ThoughtDetailComponent { - private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); private readonly service = inject(ThoughtsService); private readonly seo = inject(SeoService); @@ -184,16 +182,14 @@ export class ThoughtDetailComponent { private readonly host = inject>(ElementRef); // [ng-04 signals] The slug is a signal, and everything else derives from it. + // It used to read route.snapshot once, and the router reuses this component + // when only :slug changes, so the snapshot went stale. // - // This used to read route.snapshot once. The router reuses this component - // when only :slug changes (lesson 01 → Next → lesson 02), so the snapshot - // went stale and the page kept showing lesson 01. paramMap is an Observable - // that emits on every change. toSignal() bridges it, and requireSync works - // because ActivatedRoute replays the current params synchronously. - private readonly slug = toSignal( - this.route.paramMap.pipe(map((params) => params.get('slug') ?? '')), - { requireSync: true }, - ); + // [ng-07 routing] Lesson 04 fixed that with toSignal(route.paramMap). With + // withComponentInputBinding() in app.config.ts, the router now sets :slug + // as this input directly, and updates it on reuse. No ActivatedRoute, no + // Observable, and a spec can set it without a router at all. + readonly slug = input.required(); // computed(): derived, memoised, recomputed only when slug() changes. readonly thought = computed(() => this.service.getBySlug(this.slug())); From a1447f6b65ee9abe8a8109789c6596c474e0ac73 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:14:52 -0500 Subject: [PATCH 3/5] Add prerendered tag pages and a wildcard route --- src/app/app.routes.server.ts | 6 ++ src/app/app.routes.ts | 12 ++++ src/app/shared/seo.service.ts | 7 +- src/app/thoughts-content/thoughts-list.ts | 83 +++++++++++++++++------ 4 files changed, 83 insertions(+), 25 deletions(-) diff --git a/src/app/app.routes.server.ts b/src/app/app.routes.server.ts index ebe741d..62a19e0 100644 --- a/src/app/app.routes.server.ts +++ b/src/app/app.routes.server.ts @@ -12,6 +12,12 @@ export const serverRoutes: ServerRoute[] = [ renderMode: RenderMode.Prerender, getPrerenderParams: async () => THOUGHTS.map((thought) => ({ slug: thought.slug })), }, + { + path: 'thoughts/tag/:tag', + renderMode: RenderMode.Prerender, + getPrerenderParams: async () => + [...new Set(THOUGHTS.flatMap((thought) => thought.tags))].map((tag) => ({ tag })), + }, // The interactive desktop shell is client-rendered — hybrid rendering by route. { path: '**', diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index 737f669..3174169 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -11,9 +11,21 @@ export const routes: Routes = [ loadComponent: () => import('./thoughts-content/thoughts-list').then((m) => m.ThoughtsListComponent), }, + // [ng-07 routing] Same component as /thoughts; withComponentInputBinding() + // hands it :tag as its `tag` input. A path param rather than ?tag= so every + // tag page can be prerendered to its own static HTML file. + { + path: 'thoughts/tag/:tag', + loadComponent: () => + import('./thoughts-content/thoughts-list').then((m) => m.ThoughtsListComponent), + }, { path: 'thoughts/:slug', loadComponent: () => import('./thoughts-content/thought-detail').then((m) => m.ThoughtDetailComponent), }, + // [ng-07 routing] The wildcard goes last: the router takes the first route + // that matches, in array order, and ** matches everything. Without it, a + // mistyped URL failed the initial navigation with NG04002. + { path: '**', redirectTo: '' }, ]; diff --git a/src/app/shared/seo.service.ts b/src/app/shared/seo.service.ts index 1b07df6..ec397e6 100644 --- a/src/app/shared/seo.service.ts +++ b/src/app/shared/seo.service.ts @@ -55,9 +55,10 @@ export class SeoService { }); } - setListMeta(): void { - const url = `${SITE_ORIGIN}/thoughts`; - const pageTitle = `Thoughts — ${SITE_NAME}`; + /** The Thoughts list, or one tag's page of it. Each tag page is its own canonical URL. */ + setListMeta(tag?: string): void { + const url = tag ? `${SITE_ORIGIN}/thoughts/tag/${tag}` : `${SITE_ORIGIN}/thoughts`; + const pageTitle = tag ? `Thoughts tagged ${tag} — ${SITE_NAME}` : `Thoughts — ${SITE_NAME}`; this.title.setTitle(pageTitle); this.setName('description', LIST_DESCRIPTION); diff --git a/src/app/thoughts-content/thoughts-list.ts b/src/app/thoughts-content/thoughts-list.ts index c907149..43d72f5 100644 --- a/src/app/thoughts-content/thoughts-list.ts +++ b/src/app/thoughts-content/thoughts-list.ts @@ -1,5 +1,5 @@ -import { Component, inject } from '@angular/core'; -import { Router } from '@angular/router'; +import { Component, computed, effect, inject, input } from '@angular/core'; +import { RouterLink } from '@angular/router'; import { SeoService } from '../shared/seo.service'; import { ReadingProgressService } from './reading-progress.service'; import { ThoughtsService } from './thoughts.service'; @@ -7,19 +7,26 @@ import { UtcDatePipe } from './utc-date.pipe'; @Component({ selector: 'app-thoughts-list', - imports: [UtcDatePipe], + imports: [RouterLink, UtcDatePipe], template: `
-

Thoughts

- @for (thought of thoughts; track thought.slug) { -
-
{{ thought.title }}
+ @if (tag(); as tag) { +

Thoughts tagged “{{ tag }}”

+ ← All thoughts + } @else { +

Thoughts

+ } + @for (thought of thoughts(); track thought.slug) { + +
+

+ {{ thought.title }} +

@@ -28,11 +35,11 @@ import { UtcDatePipe } from './utc-date.pipe'; }
@for (tag of thought.tags; track tag) { - {{ tag }} + {{ tag }} }
{{ thought.summary }}
-
+ }
`, @@ -57,7 +64,15 @@ import { UtcDatePipe } from './utc-date.pipe'; margin: 0 0 16px; } + .thoughts-list-all { + display: inline-block; + margin-bottom: 16px; + font-size: 13px; + color: var(--accent-color, #007aff); + } + .thought-card { + position: relative; padding: 16px; margin-bottom: 12px; background: rgba(255, 255, 255, 0.05); @@ -71,7 +86,24 @@ import { UtcDatePipe } from './utc-date.pipe'; background: rgba(255, 255, 255, 0.08); } + .thought-card-title a { + color: inherit; + text-decoration: none; + } + + .thought-card-title a::after { + content: ''; + position: absolute; + inset: 0; + } + + .thought-card-title a:focus-visible { + outline: 2px solid var(--accent-color, #007aff); + outline-offset: 2px; + } + .thought-card-title { + margin: 0; font-size: 15px; font-weight: 600; margin-bottom: 4px; @@ -100,6 +132,9 @@ import { UtcDatePipe } from './utc-date.pipe'; } .thought-tag { + position: relative; + z-index: 1; + text-decoration: none; font-size: 10px; padding: 2px 8px; border-radius: 10px; @@ -116,17 +151,21 @@ import { UtcDatePipe } from './utc-date.pipe'; }) export class ThoughtsListComponent { private readonly service = inject(ThoughtsService); - private readonly router = inject(Router); private readonly seo = inject(SeoService); protected readonly progress = inject(ReadingProgressService); - readonly thoughts = this.service.getAll(); + /** From the :tag route param on /thoughts/tag/:tag; absent on /thoughts. */ + readonly tag = input(); - constructor() { - this.seo.setListMeta(); - } + readonly thoughts = computed(() => { + const tag = this.tag(); + const all = this.service.getAll(); + return tag ? all.filter((thought) => thought.tags.includes(tag)) : all; + }); - navigate(slug: string) { - this.router.navigate(['/thoughts', slug]); + constructor() { + // An effect, not a one-off call: moving between two tag pages reuses + // this component and only changes the input. + effect(() => this.seo.setListMeta(this.tag())); } } From 5a4f67d9c25c05b77922acd803669463d6c03049 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:17:04 -0500 Subject: [PATCH 4/5] Write lesson 07 with a route-matching playground --- .../lessons/lesson-07-routing.ts | 269 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 1 + .../thoughts-content/lessons/route-match.ts | 36 +++ src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 5 files changed, 318 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-07-routing.ts create mode 100644 src/app/thoughts-content/lessons/route-match.ts diff --git a/src/app/thoughts-content/lessons/lesson-07-routing.ts b/src/app/thoughts-content/lessons/lesson-07-routing.ts new file mode 100644 index 0000000..490f47b --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-07-routing.ts @@ -0,0 +1,269 @@ +import { Component, computed, inject, signal } from '@angular/core'; +import { PRIMARY_OUTLET, UrlSerializer } from '@angular/router'; +import { routes } from '../../app.routes'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; +import { firstMatch } from './route-match'; + +const entries = (record: Record) => + Object.entries(record).map(([key, value]) => `${key} = ${value}`); + +@Component({ + selector: 'app-lesson-07-routing', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + template: ` + +

Simple

+

+ A route maps a URL to a component. The router renders it into a + <router-outlet>, and routerLink navigates without + reloading the page. A segment starting with a colon, like :slug, is a + parameter. Here is this site's whole route table: +

+ +

+ Every link in this reader is a real <a routerLink>: the tags above, the + cards in the list, the previous and next links below. Real links prerender as + hrefs, so search engines can follow them, and middle-click and ⌘-click open a + new tab. A div with a click handler calling router.navigate() + does none of that. The Thoughts list cards were exactly that until this lesson. +

+ +

Intermediate

+

+ The router takes the first route that matches, in array order. Specific + routes go before general ones, and the ** wildcard goes last. This site didn't + have one: a mistyped URL failed the first navigation with NG04002. Now it redirects to the + desktop. +

+ +
+ + +
+
+ + +
+
+
+
Matched route
+
{{ match()?.path ?? 'no match' }}
+
Route params
+
{{ params().join(', ') || 'none' }}
+
Query params
+
{{ queryParams().join(', ') || 'none' }}
+
Fragment
+
{{ parsed().fragment ?? 'none' }}
+
+
+

+ The URL is split by Angular's own UrlSerializer. Try + /thoughts/tag/rxjs?ref=dock#top, then tick the box. +

+
+ + +

+ Route params as inputs. With withComponentInputBinding(), the + router sets path params, query params and route data as component inputs. This reader used + toSignal(route.paramMap) since lesson 04, and now declares an input instead. +

+ +

+ Path params or query params? The tag pages are + /thoughts/tag/rxjs, not /thoughts?tag=rxjs. Query params suit + optional state like sorting, filters and paging. But prerendering writes one HTML file per + path. A query-param page would be served the unfiltered list and then change + under the reader during hydration. A path gives each tag its own static page and canonical + URL. +

+

+ Lazy loading. loadComponent (and + loadChildren for a group of routes) puts a page in its own chunk, fetched on + first visit. Guards are functions: canActivate decides + whether to enter, canMatch whether the route is considered at all, and + canDeactivate whether you may leave. They return a boolean or a + UrlTree to redirect. +

+ + +

Expert

+

+ Server routes. With SSR, a second table chooses how each path renders. + This site prerenders every thought and tag page at build time and leaves the desktop + client-rendered. getPrerenderParams lists which values of a param to build. +

+ + +

+ Route reuse. By default the router reuses the component instance when + only params change, as with lesson 01 → Next → lesson 02. Anything read once + (route.snapshot, a constructor call) goes stale. Inputs and + paramMap both update. A custom RouteReuseStrategy can change + this, but making the component reactive is almost always the right fix. +

+
+

+ Also worth knowing: + withPreloading(PreloadAllModules) fetches lazy chunks after first load. + withViewTransitions() animates between routes. providers on a + route create an injector for that subtree (lesson 05). The title property, or + a custom TitleStrategy, sets the document title. For tests, + RouterTestingHarness drives the real router. This site's route specs run the + real table with the real appConfig. +

+ +

Pitfalls

+ +

+ Reading route.snapshot in a component the router reuses. + The page keeps showing the old param. Use an input or paramMap. +

+
+ +

+ An empty-path redirect without pathMatch: 'full'. Every + URL starts with an empty path, so the default prefix match redirects everything. +

+
+ +

+ Navigating from click handlers instead of links. No href, no + middle-click, nothing for crawlers or screen readers to follow. Save + router.navigate() for navigation that follows logic, like after a save. +

+
+ +

+ Relative links that are relative to the wrong thing. A + routerLink resolves against the current route, but + router.navigate(['edit']) resolves from the root unless you pass + relativeTo. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .demo-note { + font-size: 12px; + } + .route-parts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 4px 12px; + margin: 8px 0; + font-size: 13px; + } + .route-parts dt { + font-weight: 600; + } + .route-parts dd { + margin: 0; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + } + `, +}) +export class Lesson07Routing { + private readonly serializer = inject(UrlSerializer); + + protected readonly url = signal('/thoughts/tag/rxjs?ref=dock#top'); + protected readonly wildcardFirst = signal(false); + + protected readonly parsed = computed(() => this.serializer.parse(this.url())); + protected readonly match = computed(() => { + const segments = + this.parsed().root.children[PRIMARY_OUTLET]?.segments.map((segment) => segment.path) ?? []; + const table = this.wildcardFirst() + ? [...routes.filter((r) => r.path === '**'), ...routes.filter((r) => r.path !== '**')] + : routes; + return firstMatch(table, segments); + }); + protected readonly params = computed(() => entries(this.match()?.params ?? {})); + protected readonly queryParams = computed(() => entries(this.parsed().queryParams)); + + protected valueOf(event: Event): string { + return (event.target as HTMLInputElement).value; + } + + protected checked(event: Event): boolean { + return (event.target as HTMLInputElement).checked; + } + + protected readonly snippets = { + routes: `export const routes: Routes = [ + { path: '', pathMatch: 'full', children: [] }, // the desktop + { path: 'thoughts', loadComponent: () => import('./thoughts-list')... }, + { path: 'thoughts/tag/:tag', loadComponent: () => import('./thoughts-list')... }, + { path: 'thoughts/:slug', loadComponent: () => import('./thought-detail')... }, + { path: '**', redirectTo: '' }, // last, always +]; + +{{ tag }}`, + demo: `const tree = inject(UrlSerializer).parse('/thoughts/tag/rxjs?ref=dock#top'); +tree.root.children[PRIMARY_OUTLET].segments.map((s) => s.path); // ['thoughts', 'tag', 'rxjs'] +tree.queryParams; // { ref: 'dock' } +tree.fragment; // 'top' + +// then, like the router: first route in array order whose segments fit +firstMatch(routes, ['thoughts', 'tag', 'rxjs']); // { path: 'thoughts/tag/:tag', params: { tag: 'rxjs' } }`, + inputBinding: `// before (lesson 04) +private readonly route = inject(ActivatedRoute); +private readonly slug = toSignal( + this.route.paramMap.pipe(map((params) => params.get('slug') ?? '')), + { requireSync: true }, +); + +// after: app.config.ts has provideRouter(routes, withComponentInputBinding()) +readonly slug = input.required();`, + guard: `export const signedInGuard: CanActivateFn = () => { + const auth = inject(AuthService); + return auth.isSignedIn() || inject(Router).parseUrl('/sign-in'); // redirect, don't just block +}; + +{ path: 'settings', canActivate: [signedInGuard], loadComponent: ... }`, + server: `export const serverRoutes: ServerRoute[] = [ + { path: 'thoughts', renderMode: RenderMode.Prerender }, + { + path: 'thoughts/tag/:tag', + renderMode: RenderMode.Prerender, + getPrerenderParams: async () => + [...new Set(THOUGHTS.flatMap((thought) => thought.tags))].map((tag) => ({ tag })), + }, + { path: '**', renderMode: RenderMode.Client }, // the desktop: browser only +];`, + }; + + protected readonly interview = [ + { + q: 'How does the router decide which route matches?', + a: 'It walks the route array in order and takes the first route whose path fits, depth-first through children. So specific routes go before general ones, and the ** wildcard goes last. An empty-path redirect needs pathMatch: full, or it matches every URL by prefix.', + }, + { + q: 'How do you read route parameters in a component?', + a: 'Today, with withComponentInputBinding() enabled, declare an input with the param name and the router sets it, including on reuse. Without it, inject ActivatedRoute and use paramMap, an Observable, or toSignal(paramMap). Avoid route.snapshot in components the router may reuse, because it never updates.', + }, + { + q: 'What are guards and resolvers?', + a: 'Guards are functions that run during navigation. canActivate decides entry, canMatch decides whether a route is considered at all (good for feature flags and lazy loading), canDeactivate guards leaving, for example with unsaved changes. They can return a UrlTree to redirect. Resolvers fetch data before activation. Many apps now load in the component with resource() instead, so the page can render a loading state rather than blocking navigation.', + }, + { + q: 'How does lazy loading work with standalone components?', + a: 'loadComponent takes a function returning a dynamic import of a component, and loadChildren returns a routes array. The bundler splits each into its own chunk, fetched on first navigation. Preloading strategies, such as PreloadAllModules or a custom one, can fetch chunks in the background after startup.', + }, + { + q: 'Path params or query params?', + a: 'Path params identify the resource: /thoughts/:slug. Query params carry optional view state: sorting, filters, paging. With SSR or prerendering, anything that should be its own page with its own HTML and canonical URL needs to be in the path. On my site that is why tag pages are /thoughts/tag/:tag.', + }, + { + q: 'How do you test routing?', + a: 'With RouterTestingHarness: configure provideRouter with real routes, navigate by URL, and assert on the rendered component and router.url. It catches what mocked ActivatedRoute specs miss, such as component reuse on a param change. In my project a spec runs the real route table with the real app config, so a missing wildcard or router feature fails a test.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index a852a5a..9885402 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -17,4 +17,5 @@ export const LESSON_PAGES: Record Promise>> = { 'angular-04-signals': () => import('./lesson-04-signals').then((m) => m.Lesson04Signals), 'angular-05-dependency-injection': () => import('./lesson-05-di').then((m) => m.Lesson05Di), 'angular-06-rxjs': () => import('./lesson-06-rxjs').then((m) => m.Lesson06Rxjs), + 'angular-07-routing': () => import('./lesson-07-routing').then((m) => m.Lesson07Routing), }; diff --git a/src/app/thoughts-content/lessons/route-match.ts b/src/app/thoughts-content/lessons/route-match.ts new file mode 100644 index 0000000..4e1e321 --- /dev/null +++ b/src/app/thoughts-content/lessons/route-match.ts @@ -0,0 +1,36 @@ +import { Routes } from '@angular/router'; + +export interface RouteMatch { + path: string; + params: Record; +} + +/** + * [ng-07 routing] A deliberately small model of how the router picks a route, + * for lesson 07's playground: walk the array in order, take the first route + * whose segments fit, capture `:params` on the way. `**` fits anything. + * + * The real matcher also handles child routes, prefix matching, redirects, + * canMatch guards and custom matchers. This covers the flat, full-match + * routes this site actually has, which is enough to show first-match-wins. + */ +export function firstMatch(routes: Routes, segments: string[]): RouteMatch | null { + for (const route of routes) { + const path = route.path ?? ''; + if (path === '**') return { path, params: {} }; + + const parts = path.split('/').filter(Boolean); + if (parts.length !== segments.length) continue; + + const params: Record = {}; + const fits = parts.every((part, index) => { + if (part.startsWith(':')) { + params[part.slice(1)] = segments[index]; + return true; + } + return part === segments[index]; + }); + if (fits) return { path, params }; + } + return null; +} diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 0ccb002..948c46e 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -262,4 +262,7 @@ So storage became an injection token. One factory decides what storage means on 'angular-06-rxjs': `Signals took over most of what I used RxJS for, which made it easier to see what RxJS is still for: things that happen over time. A search box where the answers can come back out of order. A request that fails once and would have worked a second later. The second one was a real gap. The Projects app showed its error state on the first network blip. Now every GET goes through a small interceptor that retries transient failures twice with backoff, and never retries anything that isn't safe to send twice. The demo below is the first one: two search boxes over the same slow server, one with mergeMap and one with switchMap.`, + 'angular-07-routing': `Every thought has tags, and until now they were decoration. I wanted each tag to be a page: /thoughts/tag/angular-guide as a reading list for this series, prerendered like everything else under /thoughts. + +Wiring that up showed how much of the routing had been done by hand. The cards were divs with click handlers, so there were no real links to put the tags inside. The reader pulled its slug out of ActivatedRoute through an Observable, when the router could just hand it over as an input. And there was no wildcard route at all, so a mistyped URL failed the first navigation outright. The playground below matches URLs against this site's actual route table.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index 50d45a5..f509e55 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -242,4 +242,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'rxjs', 'angular'], relatedApp: 'projects', }, + { + slug: 'angular-07-routing', + title: 'Angular 07: Routing', + date: '2026-11-21', + summary: + 'Route order, params as inputs, path vs query params, guards and server routes, with a playground that matches URLs against this site\'s real route table. Built while turning every tag into its own prerendered page.', + tags: ['angular-guide', 'routing', 'angular'], + relatedApp: 'readme', + }, ]; From 3a9c36a81859d2a6678846670ec03bdc18c1907b Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:17:17 -0500 Subject: [PATCH 5/5] Bump to 1.4.6 with the lesson 07 changelog entry --- CHANGELOG.md | 9 +++++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 74a8069..b64e434 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ All notable changes to this project will be documented in this file. +## 2026-11-21 - version 1.4.6 + +- **Every tag has its own page**: `/thoughts/tag/`, prerendered with its own title and canonical URL, and every tag pill in the list and the reader links to it. `/thoughts/tag/angular-guide` is now the reading list for this series. It's a path param rather than `?tag=` on purpose: prerendering writes one file per path, so a query-param page would be served the unfiltered list and then change under the reader during hydration. Prerendered routes went from 27 to 74 +- **Cards are links now.** The Thoughts list cards were `div role="button"`s calling `router.navigate()`, so they had no `href` for crawlers, no middle-click, and nowhere to put the tag links (a link can't sit inside a button). The title is a real `routerLink`, and a stretched `::after` keeps the whole card clickable +- **fix: a mistyped URL failed the first navigation** with `NG04002: Cannot match any routes`. There's now a `**` route, last in the table, that redirects to the desktop +- The reader takes `:slug` as an input through `withComponentInputBinding()` instead of `toSignal(route.paramMap)`, which drops its `ActivatedRoute` and RxJS imports. A new spec runs the real route table with the real `appConfig`, so a missing route, a wildcard in the wrong place, or a router feature that's switched off fails a test +- **Angular guide, lesson 07: routing** (`/thoughts/angular-07-routing`). The playground parses a URL with Angular's own `UrlSerializer` and matches it against this site's actual route table. A checkbox moves the wildcard to the front, to show first-match-wins. Lesson 04's text now notes that lesson 07 replaced the code it shows +- Initial bundle 389.82 kB → 391.72 kB for the input-binding router feature, the two new routes and the lesson metadata. I didn't split that 1.9 kB any further + ## 2026-11-21 - version 1.4.5 - **GET requests retry transient failures.** One network blip used to put the Projects app straight into "Failed to load projects". A functional interceptor, `retryTransientErrors`, now retries any GET that fails with a network error (status 0) or a 5xx, twice, 400ms and then 800ms later. A 404 fails straight away, and nothing but GETs is ever retried, because a retried POST is a second submission diff --git a/package-lock.json b/package-lock.json index 3944857..511a96a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.5", + "version": "1.4.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.5", + "version": "1.4.6", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index 7f5a6cb..5990c57 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.5", + "version": "1.4.6", "scripts": { "ng": "ng", "start": "ng serve",