diff --git a/CHANGELOG.md b/CHANGELOG.md index bb61e5a..78f34fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to this project will be documented in this file. +## 2026-11-21 - version 1.4.1 + +- **Angular guide, lesson 02: components** (`/thoughts/angular-02-components`). Covers standalone components, `input()`, `output()`, `model()`, content projection, dynamic components and view encapsulation. The live demo is a badge whose label and tone flow in through inputs, whose count is two-way through `[(count)]`, and whose dismiss button emits an output into an event log +- **Lesson building blocks**: the layout, demo frame, callouts and interview questions that lesson 01 had inline are now components (`Lesson`, `LessonDemo`, `Callout`, `InterviewQuestions`), and lesson 01 is rebuilt on them. `Lesson` is the only `ViewEncapsulation.None` component in the app, because it has to style projected content. It scopes every selector under `.lesson` by hand +- **Copy button on code samples**: `CodeBlock` copies to the clipboard and announces "Copied" through a live region. If clipboard access is denied it says so instead of failing silently +- Callouts name their kind in text ("Pitfall", "Tip", "Expert note"), so the colour bar is never the only signal +- Initial bundle 372.98 kB → 375.71 kB. Nothing lesson-specific is eager; the growth is the `@angular/core` code behind `model()` and `output()`, which esbuild hoists into the shared core chunk once a lazy chunk uses it + ## 2026-11-21 - version 1.4.0 - **Interactive lessons in Thoughts**: a thought can now carry a lazily loaded lesson page under its prose. `thoughts-content/lessons/lessons.ts` maps slugs to loaders, and the reader loads the page through a `resource()` so SSR waits for it. The prerendered `/thoughts/angular-01-project-structure` HTML contains the whole lesson, demo included, not an empty slot. Each lesson is its own lazy chunk (lesson 01 is 13 kB), and the initial bundle is unchanged at 372.98 kB diff --git a/package-lock.json b/package-lock.json index 2257790..6b91475 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.0", + "version": "1.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.0", + "version": "1.4.1", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index f3f100f..93975e5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.0", + "version": "1.4.1", "scripts": { "ng": "ng", "start": "ng serve", diff --git a/src/app/thoughts-content/lessons/callout.ts b/src/app/thoughts-content/lessons/callout.ts new file mode 100644 index 0000000..30a3bff --- /dev/null +++ b/src/app/thoughts-content/lessons/callout.ts @@ -0,0 +1,59 @@ +import { Component, input } from '@angular/core'; + +export type CalloutKind = 'tip' | 'pitfall' | 'expert'; + +const LABELS: Record = { + tip: 'Tip', + pitfall: 'Pitfall', + expert: 'Expert note', +}; + +/** + * [ng-02 components] A presentational component: data in through inputs, + * markup in through content projection, no services, no side effects. + * + *

…

+ * + * `host` metadata binds attributes and classes onto itself, so + * there's no extra wrapper div. It's the modern replacement for @HostBinding. + */ +@Component({ + selector: 'app-callout', + host: { + role: 'note', + '[class]': '"callout callout--" + kind()', + }, + template: ` + + {{ labels[kind()] }} + + `, + styles: ` + :host { + display: block; + margin: 12px 0; + padding: 10px 14px; + border-radius: 8px; + border-left: 4px solid var(--callout-colour); + background: var(--surface-secondary, rgba(255, 255, 255, 0.04)); + } + :host(.callout--tip) { + --callout-colour: #34c759; + } + :host(.callout--pitfall) { + --callout-colour: #ff6b6b; + } + :host(.callout--expert) { + --callout-colour: #bf5af2; + } + .callout-label { + display: block; + font-size: 12px; + color: var(--text-primary, #fff); + } + `, +}) +export class Callout { + readonly kind = input.required(); + protected readonly labels = LABELS; +} diff --git a/src/app/thoughts-content/lessons/code-block.ts b/src/app/thoughts-content/lessons/code-block.ts index f4ac75d..c26b03c 100644 --- a/src/app/thoughts-content/lessons/code-block.ts +++ b/src/app/thoughts-content/lessons/code-block.ts @@ -1,4 +1,4 @@ -import { Component, input } from '@angular/core'; +import { Component, input, output, signal } from '@angular/core'; /** * A labelled, scrollable code sample for lesson pages. @@ -7,12 +7,20 @@ import { Component, input } from '@angular/core'; * Angular would try to compile `{{ }}`, `@if` and `` inside a template, * so a code sample has to be data, not markup. Interpolating a string is also * safe by default — Angular escapes it, so nothing in a sample can inject HTML. + * + * [ng-02 components] The whole public API is three members: two inputs and one + * output. Keep a component's surface that small and it stays reusable. */ @Component({ selector: 'app-code-block', template: `
-
{{ label() }}
+
+ {{ label() }} + + {{ status() }} + +
{{ code() }}
@@ -25,12 +33,32 @@ import { Component, input } from '@angular/core'; overflow: hidden; background: var(--surface-secondary, rgba(0, 0, 0, 0.25)); } - .code-block-label { - padding: 4px 12px; + .code-block-bar { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 6px 4px 12px; font-size: 11px; color: var(--text-secondary, rgba(255, 255, 255, 0.6)); border-bottom: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); } + .code-block-status { + margin-left: auto; + } + button { + font: inherit; + padding: 2px 8px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.15)); + border-radius: 5px; + background: none; + color: var(--text-primary, #fff); + cursor: pointer; + } + button:focus-visible, + pre:focus-visible { + outline: 2px solid var(--focus-ring, #4da3ff); + outline-offset: -2px; + } pre { margin: 0; padding: 12px; @@ -40,13 +68,25 @@ import { Component, input } from '@angular/core'; line-height: 1.55; color: var(--text-primary, #fff); } - pre:focus-visible { - outline: 2px solid var(--focus-ring, #4da3ff); - outline-offset: -2px; - } `, }) export class CodeBlock { readonly code = input.required(); readonly label = input('TypeScript'); + /** Emits the copied text, so a parent can react without reaching into this component. */ + readonly copied = output(); + + protected readonly status = signal(''); + + protected async copy(): Promise { + try { + await navigator.clipboard.writeText(this.code()); + this.status.set('Copied'); + this.copied.emit(this.code()); + } catch { + // Clipboard access is denied on insecure origins and in some iframes. + // Say so rather than pretending it worked. + this.status.set('Copy failed. Select the code instead'); + } + } } diff --git a/src/app/thoughts-content/lessons/interview-questions.ts b/src/app/thoughts-content/lessons/interview-questions.ts new file mode 100644 index 0000000..99e4d73 --- /dev/null +++ b/src/app/thoughts-content/lessons/interview-questions.ts @@ -0,0 +1,38 @@ +import { Component, input } from '@angular/core'; + +export interface InterviewQuestion { + q: string; + a: string; +} + +/** + * [ng-02 components] Native
/ gives a keyboard-operable, + * screen-reader-announced disclosure for free. No open/closed state to manage, + * no ARIA to get wrong. Reach for the platform before writing a toggle. + */ +@Component({ + selector: 'app-interview-questions', + template: ` + @for (item of questions(); track item.q) { +
+ {{ item.q }} +

{{ item.a }}

+
+ } + `, + styles: ` + .qa { + margin-bottom: 8px; + padding: 8px 12px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); + border-radius: 8px; + } + summary { + cursor: pointer; + color: var(--text-primary, #fff); + } + `, +}) +export class InterviewQuestions { + readonly questions = input.required(); +} diff --git a/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts b/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts index e5bc6d9..f983953 100644 --- a/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts +++ b/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts @@ -57,7 +57,7 @@ describe('Lesson01Structure', () => { to.dispatchEvent(new Event('change')); await fixture.whenStable(); - expect(el.querySelector('[role="status"]')?.textContent).toContain('Not allowed'); + expect(el.querySelector('.lesson-verdict[role="status"]')?.textContent).toContain('Not allowed'); }); it('has no axe violations', async () => { diff --git a/src/app/thoughts-content/lessons/lesson-01-structure.ts b/src/app/thoughts-content/lessons/lesson-01-structure.ts index 3d553c9..8286414 100644 --- a/src/app/thoughts-content/lessons/lesson-01-structure.ts +++ b/src/app/thoughts-content/lessons/lesson-01-structure.ts @@ -1,5 +1,8 @@ import { Component, computed, signal } from '@angular/core'; import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; export type Layer = 'shell' | 'shared' | 'feature' | 'other-feature'; @@ -49,10 +52,9 @@ const LAYER_LABELS: Record = { @Component({ selector: 'app-lesson-01-structure', - imports: [CodeBlock], + imports: [Lesson, LessonDemo, CodeBlock, InterviewQuestions], template: ` -
-

Angular guide · 01 of 13

+

Simple

@@ -87,9 +89,8 @@ const LAYER_LABELS: Record = { how a feature becomes a lazy chunk.

-
-

Try it: may this file import that one?

-
+ +
-
+
-
+
= { {{ verdict().allowed ? '✓ Allowed' : '✗ Not allowed' }}. {{ verdict().reason }}

-
+

Expert

@@ -169,61 +170,13 @@ const LAYER_LABELS: Record = {

Interview questions

- @for (qa of interview; track qa.q) { -
- {{ qa.q }} -

{{ qa.a }}

-
- } -
+ + `, styles: ` - .lesson { - margin-top: 24px; - font-size: 14px; - line-height: 1.7; - color: var(--text-secondary, rgba(255, 255, 255, 0.8)); - } - .lesson-kicker { - font-size: 12px; - text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--accent-color, #007aff); - } - h2 { - margin: 28px 0 8px; - font-size: 17px; - color: var(--text-primary, #fff); - } - h3 { - margin: 0 0 10px; - font-size: 14px; - color: var(--text-primary, #fff); - } - code { - font-family: var(--font-mono, ui-monospace, monospace); - font-size: 0.92em; - } - .lesson-demo { - margin: 16px 0; - padding: 16px; - border: 1px solid var(--accent-color, #007aff); - border-radius: 10px; - } - .lesson-demo-row { - display: flex; - align-items: center; - gap: 8px; - margin-bottom: 8px; - } - .lesson-demo-row label:first-child { + .demo-row label:first-child { min-width: 96px; } - select { - font: inherit; - padding: 4px 6px; - border-radius: 6px; - } .lesson-verdict { margin: 12px 0 0; padding: 8px 12px; @@ -236,16 +189,6 @@ const LAYER_LABELS: Record = { .lesson-verdict--bad { border-color: #ff6b6b; } - .lesson-qa { - margin-bottom: 8px; - padding: 8px 12px; - border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); - border-radius: 8px; - } - .lesson-qa summary { - cursor: pointer; - color: var(--text-primary, #fff); - } `, }) export class Lesson01Structure { diff --git a/src/app/thoughts-content/lessons/lesson-02-components.spec.ts b/src/app/thoughts-content/lessons/lesson-02-components.spec.ts new file mode 100644 index 0000000..130f299 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-02-components.spec.ts @@ -0,0 +1,57 @@ +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 { Lesson02Components } from './lesson-02-components'; + +expect.extend(axeMatchers); + +describe('Lesson02Components', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson02Components] }).compileComponents(); + fixture = TestBed.createComponent(Lesson02Components); + fixture.detectChanges(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-02-components']).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('demo: typing a label flows into the child through input()', async () => { + const label = el.querySelector('#badge-label')!; + label.value = 'Shipped'; + label.dispatchEvent(new Event('input')); + await fixture.whenStable(); + + expect(el.querySelector('app-demo-badge')?.textContent).toContain('Shipped'); + }); + + it('demo: the child increments a model() and the parent sees it', async () => { + el.querySelector('app-demo-badge .demo-badge-bump')!.click(); + await fixture.whenStable(); + + expect(el.querySelector('#badge-count-readout')?.textContent).toContain('1'); + }); + + it('demo: the child emits through output() and the parent logs it', async () => { + el.querySelector('app-demo-badge .demo-badge-dismiss')!.click(); + await fixture.whenStable(); + + expect(el.querySelector('.demo-log')?.textContent).toContain('dismissed'); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson-02-components.ts b/src/app/thoughts-content/lessons/lesson-02-components.ts new file mode 100644 index 0000000..b896649 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-02-components.ts @@ -0,0 +1,285 @@ +import { Component, input, model, output, 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'; + +type Tone = 'info' | 'warn'; + +/** + * [ng-02 components] The demo child. Every way data crosses a component + * boundary is here in one place: + * input() parent → child, read-only signal + * model() parent ⇄ child, two-way with [(count)] + * output() child → parent, an event + * parent's markup rendered inside the child + */ +@Component({ + selector: 'app-demo-badge', + host: { '[class.demo-badge--warn]': 'tone() === "warn"' }, + template: ` + + {{ label() }} + {{ count() }} + + + `, + styles: ` + :host { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 4px 6px 4px 12px; + border-radius: 999px; + border: 2px solid #0a84ff; + color: var(--text-primary, #fff); + } + :host(.demo-badge--warn) { + border-color: #ff9f0a; + border-style: dashed; + } + .demo-badge-count { + font-variant-numeric: tabular-nums; + } + button { + font: inherit; + border: none; + border-radius: 999px; + padding: 0 8px; + cursor: pointer; + } + `, +}) +export class DemoBadge { + readonly label = input.required(); + readonly tone = input('info'); + readonly count = model(0); + readonly dismissed = output(); + + protected bump(): void { + // Writing a model() updates the parent's signal through [(count)]. + // Writing an input() isn't possible at all: InputSignal has no set(). + this.count.update((n) => n + 1); + } +} + +@Component({ + selector: 'app-lesson-02-components', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions, DemoBadge], + template: ` + +

Simple

+

+ A component is a TypeScript class with a @Component decorator: a + selector (the tag you write), a template, and styles. In a standalone + component, imports lists every component, directive and pipe its template + uses. Forget one and the compiler tells you the tag is unknown. +

+ +

+ Data goes in through input() and events come out through + output(). Both are plain class fields. input() gives you a + signal, so you read it by calling it: kind(). +

+ +

Intermediate

+

+ Two-way binding is model(): the child can write it and the parent's signal + updates through [(count)]. Content projection (<ng-content>) + lets the parent pass markup rather than data, and select routes + pieces into named slots. Every lesson on this site is built that way: the layout, the demo + frame and the callouts are all projection. +

+ + +
+ + +
+
+ Tone (input) + @for (option of tones; track option) { + + } +
+
+ + + +
+

Parent's signal, via [(count)]: {{ count() }}

+
    + @for (entry of log(); track $index) { +
  1. {{ entry }}
  2. + } @empty { +
  3. No events yet. Press ✕ on the badge.
  4. + } +
+
+ + +

+ Lifecycle: with signals you rarely need hooks. Derive with computed() instead + of ngOnChanges, and clean up with inject(DestroyRef).onDestroy() + instead of ngOnDestroy. The hooks still matter for reading existing code: + ngOnInit is the first point where inputs are set, and + ngAfterViewInit is the first point where view queries resolve. +

+ +

Expert

+

+ Dynamic components. The page you are reading is one. The thought reader + doesn't know this lesson exists at compile time: it looks up a loader by slug, awaits the + import(), and hands the class to NgComponentOutlet. For + imperative cases there's ViewContainerRef.createComponent(), which takes + input bindings since v20. +

+ + +

+ app-lesson is the only component here with + ViewEncapsulation.None. Emulated encapsulation can't style projected + content, so it opts out and prefixes every selector with .lesson by hand. + That's the honest alternative to ::ng-deep, which is deprecated. +

+
+

+ Split container components (inject services, own state) from + presentational ones (inputs in, outputs out). Callout and + CodeBlock are presentational: no services, trivially reusable, trivially + testable. +

+ +

Pitfalls

+ +

+ Mutating an input object. this.user().name = 'x' changes + the parent's data behind its back, and OnPush/signals won't notice. Emit an output and + let the owner change it. +

+
+ +

+ Reading a required input in the constructor throws NG0950: inputs + aren't set yet. Read them in templates, computed() or effect(). +

+
+ +

+ Naming an output after a DOM event (click, + change): the native event bubbles too, and the handler fires twice. +

+
+ +

+ Wrapping <ng-content> in @if doesn't + lazily create the content. The parent creates projected content whether it's shown or + not. Use an ng-template input when content should be lazy. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .demo-tones { + border: none; + padding: 0; + margin: 0 0 8px; + } + .demo-tones legend { + float: left; + margin-right: 8px; + } + .demo-log { + font-size: 13px; + margin: 8px 0 0; + } + `, +}) +export class Lesson02Components { + protected readonly tones: Tone[] = ['info', 'warn']; + protected readonly label = signal('Angular'); + protected readonly tone = signal('info'); + protected readonly count = signal(0); + protected readonly log = signal([]); + + protected valueOf(event: Event): string { + return (event.target as HTMLInputElement).value; + } + + protected logEvent(label: string): void { + // A new array, not push(): signals compare by reference, so mutating in + // place would leave the list on screen stale. + this.log.update((entries) => [...entries, `dismissed → "${label}"`]); + } + + protected readonly snippets = { + callout: `@Component({ + selector: 'app-callout', + host: { role: 'note', '[class]': '"callout callout--" + kind()' }, + template: \` + {{ labels[kind()] }} + + \`, +}) +export class Callout { + readonly kind = input.required<'tip' | 'pitfall' | 'expert'>(); +}`, + parent: ` + + + ⭐ +`, + dynamic: `readonly lessonPage = resource({ + loader: () => LESSON_PAGES[this.thought?.slug ?? '']?.() ?? Promise.resolve(undefined), +}); + +// template +@if (lessonPage.value(); as page) { + +}`, + }; + + protected readonly interview = [ + { + q: 'What makes a component standalone, and why did Angular move to it?', + a: 'It declares its own dependencies in imports: [] instead of belonging to an NgModule. The dependency graph is explicit per component, lazy loading works at component granularity, and there is one fewer concept to learn. Standalone has been the default since v19.', + }, + { + q: 'input() vs @Input()?', + a: 'input() returns a read-only signal, so you derive from it with computed() and there is no need for ngOnChanges. It supports required inputs and transforms, and the compiler type-checks it. @Input() is a decorated mutable field and still everywhere in older code.', + }, + { + q: 'How does two-way binding work?', + a: 'It is sugar. [(x)]="v" expands to [x]="v" (xChange)="v = $event". model() declares both halves at once. With a signal you pass the signal itself, [(count)]="count", and Angular writes to it.', + }, + { + q: 'What is content projection and when would you use multi-slot?', + a: 'Passing markup from parent into a child through . Multi-slot uses select with a CSS selector to route parts, for example a card with header, body and footer slots. The parent still owns the projected content: it is created and change-detected as part of the parent.', + }, + { + q: 'How do you create a component dynamically?', + a: 'Declaratively with NgComponentOutlet (inputs via ngComponentOutletInputs), or imperatively with ViewContainerRef.createComponent(). Combine either with a dynamic import() so the component is its own lazy chunk. This site loads every lesson page that way.', + }, + { + q: 'What are the view encapsulation modes?', + a: 'Emulated (default) rewrites selectors with generated attributes so styles stay scoped. None makes them global. ShadowDom uses native shadow roots. Use None sparingly and scope selectors by hand. ::ng-deep is deprecated.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lesson-blocks.spec.ts b/src/app/thoughts-content/lessons/lesson-blocks.spec.ts new file mode 100644 index 0000000..0fb04e5 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-blocks.spec.ts @@ -0,0 +1,78 @@ +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 { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { LessonDemo } from './lesson-demo'; + +expect.extend(axeMatchers); + +@Component({ + imports: [Callout, LessonDemo, InterviewQuestions, CodeBlock], + template: ` +

Mutating an input array

+

Prefer input()

+ + + + `, +}) +class Host { + questions = [ + { q: 'What is a standalone component?', a: 'One that declares its own imports.' }, + { q: 'input() vs @Input()?', a: 'input() returns a signal.' }, + ]; + copiedCount = 0; +} + +describe('lesson building blocks', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + let writeText: ReturnType; + + beforeEach(async () => { + writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + await TestBed.configureTestingModule({ imports: [Host] }).compileComponents(); + fixture = TestBed.createComponent(Host); + fixture.detectChanges(); + el = fixture.nativeElement as HTMLElement; + }); + + it('Callout projects its content and labels the kind in text, not only colour', () => { + const [pitfall, tip] = [...el.querySelectorAll('app-callout')]; + expect(pitfall.getAttribute('role')).toBe('note'); + expect(pitfall.classList).toContain('callout--pitfall'); + expect(pitfall.textContent).toContain('Pitfall'); + expect(pitfall.textContent).toContain('Mutating an input array'); + expect(tip.textContent).toContain('Tip'); + }); + + it('LessonDemo wraps projected controls in a labelled region', () => { + const demo = el.querySelector('app-lesson-demo section')!; + const headingId = demo.getAttribute('aria-labelledby')!; + expect(el.querySelector(`#${headingId}`)?.textContent).toContain('Try it'); + expect(demo.querySelector('button')?.textContent).toContain('poke'); + }); + + it('InterviewQuestions renders one disclosure per question', () => { + const details = el.querySelectorAll('app-interview-questions details'); + expect(details.length).toBe(2); + expect(details[1].querySelector('summary')?.textContent).toContain('input() vs @Input()?'); + }); + + it('CodeBlock copies its code, announces it, and emits copied', async () => { + el.querySelector('app-code-block button')!.click(); + await fixture.whenStable(); + + expect(writeText).toHaveBeenCalledWith('const answer = 42;'); + expect(el.querySelector('app-code-block [role="status"]')?.textContent).toContain('Copied'); + expect(fixture.componentInstance.copiedCount).toBe(1); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson-demo.ts b/src/app/thoughts-content/lessons/lesson-demo.ts new file mode 100644 index 0000000..94fab4d --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-demo.ts @@ -0,0 +1,38 @@ +import { Component, input } from '@angular/core'; + +let nextDemoId = 0; + +/** + * [ng-02 components] A frame for a lesson's live demo. It owns the chrome + * (border, heading, landmark); the lesson projects whatever controls it needs. + * + * The id counter is per-module rather than random so the server and the + * browser generate the same ids in the same order. A random id would differ + * on hydration and break aria-labelledby. + */ +@Component({ + selector: 'app-lesson-demo', + template: ` +
+

{{ heading() }}

+ +
+ `, + styles: ` + .lesson-demo { + margin: 16px 0; + padding: 16px; + border: 1px solid var(--accent-color, #007aff); + border-radius: 10px; + } + h3 { + margin: 0 0 10px; + font-size: 14px; + color: var(--text-primary, #fff); + } + `, +}) +export class LessonDemo { + readonly heading = input.required(); + protected readonly headingId = `lesson-demo-${nextDemoId++}`; +} diff --git a/src/app/thoughts-content/lessons/lesson.ts b/src/app/thoughts-content/lessons/lesson.ts new file mode 100644 index 0000000..01cdf94 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson.ts @@ -0,0 +1,63 @@ +import { Component, input, ViewEncapsulation } from '@angular/core'; + +/** + * [ng-02 components] The shared typography for every lesson page. + * + * Expert: this is the one component in the app with ViewEncapsulation.None. + * Emulated encapsulation (the default) rewrites selectors so styles only hit + * this component's own template. The

s and s here, though, live in + * each *lesson's* template and are projected in. Encapsulated styles can't + * reach projected content without the deprecated ::ng-deep, so this component + * opts out of encapsulation and scopes itself by hand under `.lesson`. + * Without that prefix, `h2 {}` would restyle every h2 on the site. + */ +@Component({ + selector: 'app-lesson', + encapsulation: ViewEncapsulation.None, + template: ` +
+

Angular guide · {{ part() }} of 13

+ +
+ `, + styles: ` + .lesson { + margin-top: 24px; + font-size: 14px; + line-height: 1.7; + color: var(--text-secondary, rgba(255, 255, 255, 0.8)); + } + .lesson .lesson-kicker { + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--accent-color, #007aff); + } + .lesson h2 { + margin: 28px 0 8px; + font-size: 17px; + color: var(--text-primary, #fff); + } + .lesson code { + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.92em; + } + .lesson .demo-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 8px; + } + .lesson select, + .lesson input[type='text'] { + font: inherit; + padding: 4px 6px; + border-radius: 6px; + } + `, +}) +export class Lesson { + /** Two-digit part number, e.g. "02". */ + readonly part = input.required(); +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index a22a574..cf6f854 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -10,4 +10,6 @@ import { Type } from '@angular/core'; export const LESSON_PAGES: Record Promise>> = { 'angular-01-project-structure': () => import('./lesson-01-structure').then((m) => m.Lesson01Structure), + 'angular-02-components': () => + import('./lesson-02-components').then((m) => m.Lesson02Components), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 74c2ad0..231e80e 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -247,4 +247,7 @@ The payoff is measurable, which is the entire reason to reach for SSR. curl the 'angular-01-project-structure': `I am writing an Angular guide I can learn from and point to: thirteen short lessons, each one tied to a real change in this site. Every lesson goes simple, then intermediate, then expert, then the pitfalls, then the questions I would expect in an interview. The code samples are the actual code from this repo, not toy examples. This first one is about the shape of a project: what boots it, where things go, and how to keep the layering honest once there are more files than anyone can hold in their head.`, + '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.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index 7e00a56..db38826 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -197,4 +197,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'architecture', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-02-components', + title: 'Angular 02: Components', + date: '2026-11-21', + summary: + 'Standalone components, input(), output(), model() and content projection, with a live demo of data crossing a component boundary. Built while extracting the reusable blocks every lesson page now uses.', + tags: ['angular-guide', 'components', 'angular'], + relatedApp: 'readme', + }, ];