From 375d607e8726f37008b915b9fa6db5646fbfec00 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:49:09 -0500 Subject: [PATCH 1/6] Add failing specs for the double keydown, thought dates and lesson 03 --- src/app/app.spec.ts | 28 +++++++ .../lessons/lesson-03-templates.spec.ts | 75 +++++++++++++++++++ .../reading-time.pipe.spec.ts | 16 ++++ .../thoughts-content/thought-detail.spec.ts | 10 +++ 4 files changed, 129 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-03-templates.spec.ts create mode 100644 src/app/thoughts-content/reading-time.pipe.spec.ts diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index 85c63b9..0817da7 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -2,6 +2,7 @@ import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { provideRouter, Router } from '@angular/router'; import { App } from './app'; +import { KeyboardShortcutService } from './shared/keyboard-shortcut.service'; @Component({ template: '' }) class StubThought {} @@ -65,4 +66,31 @@ describe('App', () => { expect(reader.classList.contains('thoughts-reader--open')).toBe(false); }); }); + + describe('global keyboard shortcuts', () => { + const press = (init: KeyboardEventInit) => { + const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }); + document.dispatchEvent(event); + return event; + }; + + it('opens Spotlight on one ⌃⌥Space (each keydown is handled exactly once)', () => { + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + const shortcuts = TestBed.inject(KeyboardShortcutService); + + press({ code: 'Space', key: ' ', ctrlKey: true, altKey: true }); + + expect(shortcuts.spotlightOpen()).toBe(true); + }); + + it('leaves ⌘Space to the browser and macOS', () => { + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + + const event = press({ code: 'Space', key: ' ', metaKey: true }); + + expect(event.defaultPrevented).toBe(false); + }); + }); }); diff --git a/src/app/thoughts-content/lessons/lesson-03-templates.spec.ts b/src/app/thoughts-content/lessons/lesson-03-templates.spec.ts new file mode 100644 index 0000000..521efe1 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-03-templates.spec.ts @@ -0,0 +1,75 @@ +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 { Lesson03Templates } from './lesson-03-templates'; + +expect.extend(axeMatchers); + +describe('Lesson03Templates', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const click = async (selector: string) => { + el.querySelector(selector)!.click(); + await fixture.whenStable(); + }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson03Templates] }).compileComponents(); + fixture = TestBed.createComponent(Lesson03Templates); + fixture.detectChanges(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-03-templates']).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']), + ); + }); + + describe('property vs attribute demo', () => { + let probe: HTMLInputElement; + + beforeEach(() => { + probe = el.querySelector('#binding-probe')!; + probe.value = 'typed by hand'; + probe.dispatchEvent(new Event('input')); + }); + + it('[attr.value] changes the attribute but not what the box shows once typed in', async () => { + await click('#set-attribute'); + expect(probe.getAttribute('value')).toContain('attribute'); + expect(probe.value).toBe('typed by hand'); + }); + + it('[value] changes what the box shows', async () => { + await click('#set-property'); + expect(probe.value).toContain('property'); + }); + }); + + describe('control flow demo', () => { + it('removes a tag and switches the summary as the count changes', async () => { + const summary = () => el.querySelector('#tag-summary')?.textContent ?? ''; + expect(summary()).toContain('3 tags'); + + await click('.tag-remove'); + await click('.tag-remove'); + expect(summary()).toContain('One tag'); + + await click('.tag-remove'); + expect(summary()).toContain('No tags'); + expect(el.querySelector('.tag-list')?.textContent).toContain('All gone'); + }); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/reading-time.pipe.spec.ts b/src/app/thoughts-content/reading-time.pipe.spec.ts new file mode 100644 index 0000000..c0de59d --- /dev/null +++ b/src/app/thoughts-content/reading-time.pipe.spec.ts @@ -0,0 +1,16 @@ +import { ReadingTimePipe } from './reading-time.pipe'; + +describe('ReadingTimePipe', () => { + const pipe = new ReadingTimePipe(); + const words = (count: number) => Array.from({ length: count }, () => 'word').join(' '); + + it('rounds up at 200 words a minute', () => { + expect(pipe.transform(words(200))).toBe('1 min read'); + expect(pipe.transform(words(201))).toBe('2 min read'); + }); + + it('never reports zero, and ignores extra whitespace', () => { + expect(pipe.transform('')).toBe('1 min read'); + expect(pipe.transform(' one \n\n two ')).toBe('1 min read'); + }); +}); diff --git a/src/app/thoughts-content/thought-detail.spec.ts b/src/app/thoughts-content/thought-detail.spec.ts index 2d244f0..3f154bf 100644 --- a/src/app/thoughts-content/thought-detail.spec.ts +++ b/src/app/thoughts-content/thought-detail.spec.ts @@ -58,6 +58,16 @@ describe('ThoughtDetailComponent', () => { expect(tagTexts).toContain('angular'); }); + 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 + // the 'UTC' argument any timezone west of UTC renders June 14. + expect(nativeEl.querySelector('.thought-detail-date')?.textContent).toContain('Jun 15, 2026'); + }); + + it('shows a reading time for a prose thought', () => { + expect(nativeEl.querySelector('.thought-detail-date')?.textContent).toContain('min read'); + }); + it('should set SEO metadata for the thought', () => { expect(document.title).toContain('Why Angular Signals Changed Everything'); }); From 3d5d569a38e07bee795f12c0137c312701cec911 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:49:48 -0500 Subject: [PATCH 2/6] Add a failing spec for formatted dates on thought cards --- src/app/thoughts-content/thoughts-list.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/app/thoughts-content/thoughts-list.spec.ts b/src/app/thoughts-content/thoughts-list.spec.ts index 0f946ff..c665c6e 100644 --- a/src/app/thoughts-content/thoughts-list.spec.ts +++ b/src/app/thoughts-content/thoughts-list.spec.ts @@ -25,6 +25,11 @@ describe('ThoughtsListComponent', () => { nativeEl = fixture.nativeElement as HTMLElement; }); + it('formats card dates in UTC, like the reader does', () => { + const dates = [...nativeEl.querySelectorAll('.thought-card-date')].map((d) => d.textContent); + expect(dates).toContain('Jun 15, 2026'); + }); + it('should render a card for each thought entry', () => { const service = TestBed.inject(ThoughtsService); const cards = nativeEl.querySelectorAll('.thought-card'); From 447f9c4cc20841362ace72e2057c37dda76b924e Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:52:47 -0500 Subject: [PATCH 3/6] Handle each desktop keydown once and stop swallowing Cmd+Space --- src/app/app.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/app/app.ts b/src/app/app.ts index f4f3c93..708be3c 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,5 +1,5 @@ import { NgComponentOutlet } from '@angular/common'; -import { Component, effect, HostListener, inject, viewChild } from '@angular/core'; +import { Component, effect, inject, viewChild } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; import { NavigationEnd, Router, RouterOutlet } from '@angular/router'; import { filter, map } from 'rxjs'; @@ -32,6 +32,10 @@ import { WindowManagerService } from './window-manager/window-manager.service'; ], templateUrl: './app.html', styleUrl: './app.css', + // [ng-03 templates] Event binding on the host, or here on `document`. + // Preferred over @HostListener: it's plain metadata, it's type-checked + // against the class, and it's the style the Angular team now recommends. + host: { '(document:keydown)': 'onKeydown($event)' }, }) export class App { protected readonly launcher = inject(AppLauncherService); @@ -76,17 +80,17 @@ export class App { }); } - @HostListener('document:keydown', ['$event']) + // [ng-03 templates] Bound through `host: { '(document:keydown)': … }` above. + // This used to call handleKeydown twice, so every toggle shortcut flipped + // and flipped back: ⌃⌥Space never opened Spotlight. It also still + // preventDefault()ed ⌘Space, which the 1.3.4 remap meant to hand back to + // the browser. One event, one handler call. onKeydown(event: KeyboardEvent): void { if (event.key === 'Escape' && this.onThoughtsRoute()) { this.closeThoughts(); return; } this.shortcuts.handleKeydown(event); - if (event.metaKey && event.code === 'Space') { - event.preventDefault(); - } - this.shortcuts.handleKeydown(event); } toggleSpotlight(): void { From 46a5bd554f2ef9584c882e6166473e68075452ff Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:52:47 -0500 Subject: [PATCH 4/6] Format thought dates in UTC and show reading time --- src/app/thoughts-content/reading-time.pipe.ts | 19 +++++++++++++ src/app/thoughts-content/thought-detail.ts | 16 +++++++++-- src/app/thoughts-content/thoughts-list.ts | 7 ++++- .../thoughts-content/utc-date.pipe.spec.ts | 14 ++++++++++ src/app/thoughts-content/utc-date.pipe.ts | 28 +++++++++++++++++++ 5 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 src/app/thoughts-content/reading-time.pipe.ts create mode 100644 src/app/thoughts-content/utc-date.pipe.spec.ts create mode 100644 src/app/thoughts-content/utc-date.pipe.ts diff --git a/src/app/thoughts-content/reading-time.pipe.ts b/src/app/thoughts-content/reading-time.pipe.ts new file mode 100644 index 0000000..1541012 --- /dev/null +++ b/src/app/thoughts-content/reading-time.pipe.ts @@ -0,0 +1,19 @@ +import { Pipe, PipeTransform } from '@angular/core'; + +const WORDS_PER_MINUTE = 200; + +/** + * [ng-03 templates] A custom pipe: `{{ thought.content | readingTime }}`. + * + * Pipes are pure by default, so Angular only re-runs transform() when the + * input reference changes. That makes a pipe the right place for a derivation + * that's called from a template. A method call like `{{ readingTime(text) }}` + * re-runs on every change detection pass that touches this view. + */ +@Pipe({ name: 'readingTime' }) +export class ReadingTimePipe implements PipeTransform { + transform(text: string): string { + const words = text.split(/\s+/).filter(Boolean).length; + return `${Math.max(1, Math.ceil(words / WORDS_PER_MINUTE))} min read`; + } +} diff --git a/src/app/thoughts-content/thought-detail.ts b/src/app/thoughts-content/thought-detail.ts index ab807c0..21fa16b 100644 --- a/src/app/thoughts-content/thought-detail.ts +++ b/src/app/thoughts-content/thought-detail.ts @@ -3,17 +3,26 @@ import { Component, inject, resource } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { SeoService } from '../shared/seo.service'; import { LESSON_PAGES } from './lessons/lessons'; +import { ReadingTimePipe } from './reading-time.pipe'; +import { UtcDatePipe } from './utc-date.pipe'; import { ThoughtsService } from './thoughts.service'; @Component({ selector: 'app-thought-detail', - imports: [NgComponentOutlet], + imports: [NgComponentOutlet, UtcDatePipe, ReadingTimePipe], template: ` @if (thought) {

{{ thought.title }}

-
{{ thought.date }}
+ +
+ + @if (!hasLessonPage) { + · {{ thought.content | readingTime }} + } +
@for (tag of thought.tags; track tag) { {{ tag }} @@ -106,6 +115,9 @@ export class ThoughtDetailComponent { readonly thought = this.service.getBySlug(this.route.snapshot.paramMap.get('slug') ?? ''); + // Lesson pages are mostly interactive, so a word count of the intro would undersell them. + readonly hasLessonPage = !!this.thought && this.thought.slug in LESSON_PAGES; + // A resource rather than a bare promise: while it loads it holds a pending // task, so SSR prerendering waits for the lesson chunk and bakes the full // interactive page into the static HTML instead of an empty slot. diff --git a/src/app/thoughts-content/thoughts-list.ts b/src/app/thoughts-content/thoughts-list.ts index 9b82e6a..fb46cdd 100644 --- a/src/app/thoughts-content/thoughts-list.ts +++ b/src/app/thoughts-content/thoughts-list.ts @@ -2,9 +2,11 @@ import { Component, inject } from '@angular/core'; import { Router } from '@angular/router'; import { SeoService } from '../shared/seo.service'; import { ThoughtsService } from './thoughts.service'; +import { UtcDatePipe } from './utc-date.pipe'; @Component({ selector: 'app-thoughts-list', + imports: [UtcDatePipe], template: `

Thoughts

@@ -17,7 +19,9 @@ import { ThoughtsService } from './thoughts.service'; (keydown.enter)="navigate(thought.slug)" >
{{ thought.title }}
-
{{ thought.date }}
+
@for (tag of thought.tags; track tag) { {{ tag }} @@ -70,6 +74,7 @@ import { ThoughtsService } from './thoughts.service'; } .thought-card-date { + display: block; font-size: 11px; color: var(--text-secondary, rgba(255, 255, 255, 0.5)); margin-bottom: 8px; diff --git a/src/app/thoughts-content/utc-date.pipe.spec.ts b/src/app/thoughts-content/utc-date.pipe.spec.ts new file mode 100644 index 0000000..feea0d4 --- /dev/null +++ b/src/app/thoughts-content/utc-date.pipe.spec.ts @@ -0,0 +1,14 @@ +import { UtcDatePipe } from './utc-date.pipe'; + +describe('UtcDatePipe', () => { + const pipe = new UtcDatePipe(); + + it('formats a YYYY-MM-DD as a medium date without shifting the day', () => { + expect(pipe.transform('2026-06-15')).toBe('Jun 15, 2026'); + expect(pipe.transform('2026-01-01')).toBe('Jan 1, 2026'); + }); + + it('fails loudly on a date it cannot parse instead of printing "Invalid Date"', () => { + expect(() => pipe.transform('not-a-date')).toThrow(/not-a-date/); + }); +}); diff --git a/src/app/thoughts-content/utc-date.pipe.ts b/src/app/thoughts-content/utc-date.pipe.ts new file mode 100644 index 0000000..6e796e1 --- /dev/null +++ b/src/app/thoughts-content/utc-date.pipe.ts @@ -0,0 +1,28 @@ +import { Pipe, PipeTransform } from '@angular/core'; + +// Built once at module load; constructing an Intl formatter per call is the slow part. +const MEDIUM_UTC = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' }); + +/** + * [ng-03 templates] `{{ thought.date | utcDate }}` → "Jun 15, 2026". + * + * Why not `| date: 'mediumDate' : 'UTC'`? That was the first version, and the + * production build said no: initial bundle +13 kB. @angular/common ships as + * one module that this app already loads eagerly, so using DatePipe anywhere, + * even in a lazy route, pulls its locale formatting into the initial chunk. + * The platform's Intl API does the same job in a few lines for free. + * + * The 'UTC' timezone is the bit that matters either way: '2026-06-15' parses as + * UTC midnight, so formatting in local time shows the 14th west of Greenwich, + * and a server in another zone would render a different day than the browser. + */ +@Pipe({ name: 'utcDate' }) +export class UtcDatePipe implements PipeTransform { + transform(isoDate: string): string { + const parsed = new Date(isoDate); + if (Number.isNaN(parsed.getTime())) { + throw new Error(`utcDate: cannot parse "${isoDate}" as a date`); + } + return MEDIUM_UTC.format(parsed); + } +} From 42043eb9241b67452bb5e9a52ae087049f9e8666 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:52:47 -0500 Subject: [PATCH 5/6] Write lesson 03 with property-vs-attribute and control-flow demos --- .../lessons/lesson-03-templates.ts | 280 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 2 + src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 4 files changed, 294 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-03-templates.ts diff --git a/src/app/thoughts-content/lessons/lesson-03-templates.ts b/src/app/thoughts-content/lessons/lesson-03-templates.ts new file mode 100644 index 0000000..e9ebcd8 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-03-templates.ts @@ -0,0 +1,280 @@ +import { Component, signal } 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'; + +const STARTING_TAGS = ['signals', 'pipes', 'control-flow']; + +@Component({ + selector: 'app-lesson-03-templates', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + template: ` + +

Simple

+

+ A template is HTML with four kinds of binding. {{ literal.interpolation }} + interpolates text, [prop]="expr" sets a DOM property, + (event)="handler()" listens, and [(x)]="signal" does both. Control + flow is built in: @if/@else, @for and + @switch. Pipes format values on the way out: + {{ literal.pipe }}. +

+ +

+ @for requires a track expression. It's how Angular knows which + DOM row belongs to which item when the list changes, so it can move rows instead of + rebuilding them. +

+ +

Intermediate

+

+ Properties are not attributes. An attribute is the initial value written + in the HTML; a property is the live value on the DOM object. [value] sets the + property. [attr.value] sets the attribute, which an input ignores once someone + has typed in it. Use [attr.x] only where no property exists: + aria-*, colspan, SVG. +

+ + +

Type something in the box, then press each button.

+
+ + +
+
+ + +
+

{{ explanation() }}

+
+ +

+ The rest of the everyday toolkit: [class.active]="on" and + [style.width.px]="w" for single classes and styles; + #ref template variables to grab an element or component; + @let to name a value once; key filters like + (keydown.enter); and $index, $first, + $last, $count inside @for. +

+ + +
    + @for (tag of tags(); track tag; let position = $index, isLast = $last) { +
  • + {{ position + 1 }}. {{ tag }}{{ isLast ? ' (last)' : '' }} + +
  • + } @empty { +
  • All gone.
  • + } +
+ @let count = tags().length; +

+ @switch (count) { + @case (0) { No tags left. } + @case (1) { One tag left. } + @default { {{ count }} tags left. } + } +

+
+ + +

Expert

+

+ Pipes are pure by default: transform() only re-runs when its + input reference changes. A method call in a template, like + {{ literal.methodCall }}, runs on every change detection pass that + checks the view. This site's reading time is a pure pipe for that reason. Impure pipes + (pure: false) run every pass; async is the famous one. +

+ + +

+ The dates on this site first used | date: 'mediumDate' : 'UTC'. The + production build put the initial bundle up 13 kB, even though both + thought views are lazy. @angular/common ships as one module that the app + already loads eagerly, so DatePipe's locale formatting landed in the initial + chunk. A five-line utcDate pipe over Intl.DateTimeFormat + prints the same "Jun 15, 2026" for free. Read the build output, not just the tests. +

+
+

+ Host event bindings. Listen on the component's own element, or on + window/document, through host metadata. That's + preferred over @HostListener. Writing this lesson turned up a real bug in the + desktop's handler: it called the shortcut service twice per keydown, so ⌃⌥Space + opened Spotlight and immediately closed it again. +

+ +

+ Under the sugar: the old *ngIf/*ngFor desugar to + <ng-template> plus a directive. You'll meet them in every pre-v17 + codebase, along with ngTemplateOutlet for passing a reusable template and + context into a child. The built-in control flow compiles to instructions directly, needs no + import, and type-narrows inside @if. +

+ +

+ Angular sanitizes [innerHTML], [href] and + [style] values automatically. DomSanitizer.bypassSecurityTrust* + turns that off, so every call to it deserves a code-review comment explaining why the + input can be trusted. +

+
+ +

Pitfalls

+ +

+ track $index on a list that reorders or deletes. Rows get + reused for the wrong items, so focus, input text and animations jump to the neighbour. + Track a stable id. +

+
+ +

+ Timezones in date formatting. '2026-06-15' parses as UTC + midnight. Format it in local time (what | date does unless you pass + 'UTC') and everyone west of Greenwich sees June 14, while an SSR server in + another zone renders a different date than the browser hydrates. +

+
+ +

+ A <button> inside a <form> defaults + to type="submit". Every non-submit button needs type="button". +

+
+ +

+ Expensive work in template expressions. Filtering or sorting in a method + the template calls runs it on every check. Move it into a computed() or a pure + pipe. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .tag-list { + margin: 0; + padding-left: 0; + list-style: none; + } + .tag-list li { + margin-bottom: 6px; + } + `, +}) +export class Lesson03Templates { + // Literal template syntax shown in prose. Interpolated strings are never + // re-parsed as template, so binding them is the safe way to print "{{". + protected readonly literal = { + interpolation: '{{ value }}', + pipe: "{{ date | date: 'mediumDate' }}", + methodCall: '{{ readingTime(text) }}', + }; + + protected readonly propertyValue = signal(''); + protected readonly attributeValue = signal(''); + protected readonly explanation = signal('Nothing set yet.'); + private presses = 0; + + protected setAttribute(): void { + this.attributeValue.set(`attribute #${++this.presses}`); + this.explanation.set( + 'The value attribute changed (check devtools), but once you have typed, the box keeps showing your text.', + ); + } + + protected setProperty(): void { + this.propertyValue.set(`property #${++this.presses}`); + this.explanation.set('The value property changed, and the box shows it straight away.'); + } + + protected readonly tags = signal(STARTING_TAGS); + + protected remove(tag: string): void { + this.tags.update((tags) => tags.filter((t) => t !== tag)); + } + + protected resetTags(): void { + this.tags.set(STARTING_TAGS); + } + + protected readonly snippets = { + detail: `

{{ thought.title }}

+ +@if (!hasLessonPage) { + · {{ thought.content | readingTime }} +} +@for (tag of thought.tags; track tag) { + {{ tag }} +}`, + controlFlow: `@for (tag of tags(); track tag; let position = $index, isLast = $last) { +
  • + {{ position + 1 }}. {{ tag }}{{ isLast ? ' (last)' : '' }} + +
  • +} @empty { +
  • All gone.
  • +} + +@let count = tags().length; +@switch (count) { + @case (0) { No tags left. } + @case (1) { One tag left. } + @default { {{ count }} tags left. } +}`, + pipe: `@Pipe({ name: 'readingTime' }) +export class ReadingTimePipe implements PipeTransform { + transform(text: string): string { + const words = text.split(/\\s+/).filter(Boolean).length; + return \`\${Math.max(1, Math.ceil(words / 200))} min read\`; + } +}`, + hostListener: `// Before: every toggle fired twice, so ⌃⌥Space opened and closed Spotlight +@HostListener('document:keydown', ['$event']) +onKeydown(event: KeyboardEvent): void { + this.shortcuts.handleKeydown(event); + if (event.metaKey && event.code === 'Space') event.preventDefault(); + this.shortcuts.handleKeydown(event); +} + +// After: binding declared as metadata, one call per event +@Component({ host: { '(document:keydown)': 'onKeydown($event)' } }) +onKeydown(event: KeyboardEvent): void { + this.shortcuts.handleKeydown(event); +}`, + }; + + protected readonly interview = [ + { + q: "What's the difference between property binding and attribute binding?", + a: '[x] sets the DOM property, the live value. [attr.x] sets the HTML attribute, the initial value. They diverge for things like an input value after typing. Use attr only when there is no property, such as aria-*, colspan or SVG attributes.', + }, + { + q: 'Why does @for require track, and what should you track by?', + a: 'track lets Angular map items to DOM rows across changes, so it can move or keep rows instead of recreating them. Track a stable unique id. $index is only safe for static lists that never reorder or delete.', + }, + { + q: 'Pure vs impure pipes?', + a: "A pure pipe re-runs only when its input reference changes, so it is effectively memoised per binding. An impure pipe runs on every change detection pass. Most custom pipes should be pure. AsyncPipe is the classic impure one, because it has to check for new emissions.", + }, + { + q: 'Built-in control flow vs *ngIf / *ngFor?', + a: "@if, @for and @switch are part of the template language. They need no imports, @if narrows types, @for makes tracking mandatory and has @empty, and they're faster. The structural directives desugar to ng-template plus a directive and are still common in older code. There's an automatic migration: ng generate @angular/core:control-flow.", + }, + { + q: 'How do you listen to a global event like keydown on document?', + a: "host: { '(document:keydown)': 'onKey($event)' } in the component metadata, or @HostListener in older code. Both clean themselves up when the component is destroyed. Never add a raw addEventListener without removing it in DestroyRef.", + }, + { + q: 'How does Angular protect against XSS in templates?', + a: 'Interpolation is always text-escaped, and values bound into innerHTML, URLs and styles are sanitized by context. bypassSecurityTrust* disables that for one value, so it should only ever see trusted input.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index cf6f854..74f93c6 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -12,4 +12,6 @@ export const LESSON_PAGES: Record Promise>> = { import('./lesson-01-structure').then((m) => m.Lesson01Structure), 'angular-02-components': () => import('./lesson-02-components').then((m) => m.Lesson02Components), + 'angular-03-templates': () => + import('./lesson-03-templates').then((m) => m.Lesson03Templates), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 231e80e..2315cbe 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -250,4 +250,7 @@ This first one is about the shape of a project: what boots it, where things go, 'angular-02-components': `Lesson one's page had all its layout, demo frame and Q&A markup inline. Copying that twelve more times would have been the wrong move, so this lesson is the refactor: the page is now built from small components (a layout, a demo frame, callouts, an interview-question list, and a code block that copies to the clipboard), and lesson one was rebuilt on them. That makes components the natural topic: what goes in through inputs, what comes out through outputs, what gets projected, and when a component should own nothing at all.`, + 'angular-03-templates': `Templates are where most Angular bugs live, because a binding looks right whether or not it is. Writing this lesson turned up two in this site. The desktop's keydown handler called the shortcut service twice per event, so the Spotlight shortcut opened it and closed it again in the same keypress. And every thought date was printed raw. The obvious fix, the date pipe, would have shown the day before for anyone behind UTC, because a bare YYYY-MM-DD parses as UTC midnight. + +Both are fixed now, and both are in the lesson as the pitfalls they are.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index db38826..94337fd 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -206,4 +206,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'components', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-03-templates', + title: 'Angular 03: Templates and binding', + date: '2026-11-21', + summary: + 'Property vs attribute binding, built-in control flow, pipes and host event bindings. Writing it turned up a keyboard handler that ran twice per keypress, and dates that would have shown the day before for half the world.', + tags: ['angular-guide', 'templates', 'angular'], + relatedApp: 'readme', + }, ]; From 7df9d1012ef6d01cf830e69e6c9a0861c02976c0 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:53:05 -0500 Subject: [PATCH 6/6] Bump to 1.4.2 with the lesson 03 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 78f34fe..f242993 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.2 + +- **fix: ⌃⌥Space never opened Spotlight.** `App.onKeydown` called `shortcuts.handleKeydown(event)` twice per keydown, so every toggle shortcut flipped and flipped straight back, and ⌃⌥Tab cycled two windows at a time. It's now bound once through `host: { '(document:keydown)': … }` instead of `@HostListener` +- **fix: ⌘Space was still swallowed.** The same handler kept a `preventDefault()` on ⌘Space that the 1.3.4 remap meant to remove, so the real macOS Spotlight shortcut did nothing while the site had focus. Specs now pin both: one ⌃⌥Space opens Spotlight, and ⌘Space is left un-prevented +- **Readable thought dates**: cards and the reader show "Jun 15, 2026" instead of `2026-06-15`, inside a `