From 919907dc4ea7322dfb1263208e7dc429d40320ef Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:18:52 -0500 Subject: [PATCH 1/4] Add failing specs for contact form validation and lesson 08 --- src/app/apps/contact-app.spec.ts | 70 +++++++++++++++---- src/app/shared/validators.spec.ts | 12 ++++ .../lessons/lesson-08-forms.spec.ts | 68 ++++++++++++++++++ 3 files changed, 136 insertions(+), 14 deletions(-) create mode 100644 src/app/shared/validators.spec.ts create mode 100644 src/app/thoughts-content/lessons/lesson-08-forms.spec.ts diff --git a/src/app/apps/contact-app.spec.ts b/src/app/apps/contact-app.spec.ts index 8c26fee..fde5423 100644 --- a/src/app/apps/contact-app.spec.ts +++ b/src/app/apps/contact-app.spec.ts @@ -1,6 +1,10 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../test/a11y'; import { ContactApp } from './contact-app'; +expect.extend(axeMatchers); + describe('ContactApp', () => { let fixture: ComponentFixture; let component: ContactApp; @@ -23,9 +27,57 @@ describe('ContactApp', () => { expect(nativeEl.querySelector('textarea[formControlName="message"]')).toBeTruthy(); }); - it('should disable the submit button when the form is invalid', () => { + // [ng-08 forms] Send used to be disabled until the form was valid. A + // disabled button can't be focused, explains nothing, and leaves someone + // who can't see the inline errors with no idea what's wrong. Now it's always + // enabled, and pressing it on an invalid form shows every error. + it('keeps Send enabled, so pressing it can explain what is missing', () => { const btn = nativeEl.querySelector('.contact-submit') as HTMLButtonElement; - expect(btn.disabled).toBe(true); + expect(btn.disabled).toBe(false); + }); + + it('submitting an invalid form shows every error, focuses the first bad field, and sends nothing', async () => { + component.form.controls.name.setValue('Paul'); + (nativeEl.querySelector('.contact-submit') as HTMLButtonElement).click(); + await fixture.whenStable(); + + expect(nativeEl.querySelector('.contact-error-email')).toBeTruthy(); + expect(nativeEl.querySelector('.contact-error-message')).toBeTruthy(); + expect(nativeEl.querySelector('.contact-error-name')).toBeNull(); + expect(document.activeElement?.id).toBe('contact-email'); + expect(component.submissionStatus()).toBe('idle'); + }); + + it('rejects a name or message that is only whitespace', () => { + component.form.setValue({ name: ' ', email: 'test@example.com', message: '\n\t ' }); + + expect(component.form.controls.name.hasError('blank')).toBe(true); + expect(component.form.controls.message.hasError('blank')).toBe(true); + expect(component.form.valid).toBe(false); + }); + + it('ties each shown error to its field with aria-invalid and aria-describedby', async () => { + component.form.controls.email.setValue('not-an-email'); + component.form.controls.email.markAsTouched(); + fixture.detectChanges(); + await fixture.whenStable(); + + const email = nativeEl.querySelector('#contact-email')!; + const describedBy = email.getAttribute('aria-describedby'); + expect(email.getAttribute('aria-invalid')).toBe('true'); + expect(describedBy).toBeTruthy(); + expect(nativeEl.querySelector(`#${describedBy}`)?.textContent).toContain('Valid email'); + + const name = nativeEl.querySelector('#contact-name')!; + expect(name.getAttribute('aria-invalid')).toBeNull(); + expect(name.getAttribute('aria-describedby')).toBeNull(); + }); + + it('has no axe violations while errors are showing', async () => { + component.form.markAllAsTouched(); + fixture.detectChanges(); + await fixture.whenStable(); + expect(await axe(nativeEl)).toHaveNoViolations(); }); it('should show a validation error when name is empty and touched', () => { @@ -57,18 +109,6 @@ describe('ContactApp', () => { expect(error).toBeTruthy(); }); - it('should enable the submit button when the form is valid', () => { - component.form.setValue({ - name: 'Test User', - email: 'test@example.com', - message: 'Hello!', - }); - fixture.detectChanges(); - - const btn = nativeEl.querySelector('.contact-submit') as HTMLButtonElement; - expect(btn.disabled).toBe(false); - }); - it('should call the submission handler when a valid form is submitted', () => { component.form.setValue({ name: 'Test User', @@ -111,6 +151,8 @@ describe('ContactApp', () => { const success = nativeEl.querySelector('.contact-success'); expect(success).toBeTruthy(); + // Announced, not just painted: screen readers hear a live region change. + expect(success?.getAttribute('role')).toBe('status'); }); it('should reset the form after successful submission', async () => { diff --git a/src/app/shared/validators.spec.ts b/src/app/shared/validators.spec.ts new file mode 100644 index 0000000..e3f2125 --- /dev/null +++ b/src/app/shared/validators.spec.ts @@ -0,0 +1,12 @@ +import { FormControl } from '@angular/forms'; +import { notBlank } from './validators'; + +describe('notBlank', () => { + it.each(['', ' ', '\n\t '])('flags %j as blank', (value) => { + expect(notBlank(new FormControl(value))).toEqual({ blank: true }); + }); + + it('passes text with something in it, even with spaces around', () => { + expect(notBlank(new FormControl(' hi '))).toBeNull(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts b/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts new file mode 100644 index 0000000..5107238 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts @@ -0,0 +1,68 @@ +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 { Lesson08Forms } from './lesson-08-forms'; + +expect.extend(axeMatchers); + +describe('Lesson08Forms', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const text = (selector: string) => el.querySelector(selector)?.textContent ?? ''; + const type = async (selector: string, value: string) => { + const input = el.querySelector(selector)!; + input.value = value; + input.dispatchEvent(new Event('input')); + input.dispatchEvent(new Event('blur')); + await fixture.whenStable(); + }; + const click = async (selector: string) => { + el.querySelector(selector)!.click(); + await fixture.whenStable(); + }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson08Forms] }).compileComponents(); + fixture = TestBed.createComponent(Lesson08Forms); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-08-forms']).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('flags mismatched passwords with a group-level validator, and clears it when they match', async () => { + await type('#demo-password', 'correct horse'); + await type('#demo-confirm', 'correct house'); + expect(text('#demo-mismatch')).toContain("don't match"); + + await type('#demo-confirm', 'correct horse'); + expect(el.querySelector('#demo-mismatch')).toBeNull(); + expect(text('#demo-form-state')).toContain('VALID'); + }); + + it('adds and removes rows in a FormArray', async () => { + const rows = () => el.querySelectorAll('.demo-link-row').length; + expect(rows()).toBe(1); + + await click('#demo-add-link'); + expect(rows()).toBe(2); + + await click('.demo-link-row:last-child .demo-remove-link'); + expect(rows()).toBe(1); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); From 80d43d3402d0c7fb126a4a3435b91ec4c8198783 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:19:50 -0500 Subject: [PATCH 2/4] Explain contact form errors instead of disabling Send --- src/app/apps/contact-app.spec.ts | 5 +- src/app/apps/contact-app.ts | 97 ++++++++++++++++++++++--------- src/app/shared/validators.spec.ts | 4 +- src/app/shared/validators.ts | 12 ++++ 4 files changed, 87 insertions(+), 31 deletions(-) create mode 100644 src/app/shared/validators.ts diff --git a/src/app/apps/contact-app.spec.ts b/src/app/apps/contact-app.spec.ts index fde5423..952902f 100644 --- a/src/app/apps/contact-app.spec.ts +++ b/src/app/apps/contact-app.spec.ts @@ -151,8 +151,9 @@ describe('ContactApp', () => { const success = nativeEl.querySelector('.contact-success'); expect(success).toBeTruthy(); - // Announced, not just painted: screen readers hear a live region change. - expect(success?.getAttribute('role')).toBe('status'); + // Announced, not just painted: it's inside a live region that was + // already in the DOM, so screen readers hear the change. + expect(success?.closest('[role="status"]')).toBeTruthy(); }); it('should reset the form after successful submission', async () => { diff --git a/src/app/apps/contact-app.ts b/src/app/apps/contact-app.ts index e464585..2a4142b 100644 --- a/src/app/apps/contact-app.ts +++ b/src/app/apps/contact-app.ts @@ -1,5 +1,6 @@ -import { Component, inject, signal } from '@angular/core'; +import { Component, ElementRef, inject, signal } from '@angular/core'; import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; +import { notBlank } from '../shared/validators'; type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error'; @@ -12,20 +13,41 @@ type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error';

New Message

-
+ + +
- - @if (form.controls.name.touched && form.controls.name.invalid) { - Name is required + + @if (showError('name')) { + Name is required }
- - @if (form.controls.email.touched && form.controls.email.invalid) { - Valid email is required + + @if (showError('email')) { + Valid email is required }
@@ -36,31 +58,37 @@ type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error'; formControlName="message" placeholder="Your message..." rows="6" + [attr.aria-invalid]="showError('message') || null" + [attr.aria-describedby]="showError('message') ? 'contact-message-error' : null" > - @if (form.controls.message.touched && form.controls.message.invalid) { - Message is required + @if (showError('message')) { + Message is required } +
-
- @if (submissionStatus() === 'pending') { -
Sending message...
- } - @if (submissionStatus() === 'success') { -
Message sent successfully!
- } - @if (submissionStatus() === 'error') { -
Failed to send message. Please try again.
- } + +
+ @if (submissionStatus() === 'pending') { +
Sending message...
+ } + @if (submissionStatus() === 'success') { +
Message sent successfully!
+ } + @if (submissionStatus() === 'error') { +
Failed to send message. Please try again.
+ } +
`, @@ -191,17 +219,32 @@ type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error'; }) export class ContactApp { private readonly fb = inject(FormBuilder); + private readonly host = inject>(ElementRef); + // [ng-08 forms] nonNullable: reset() goes back to '' rather than null, so + // the value type is string, not string | null. readonly form = this.fb.nonNullable.group({ - name: ['', Validators.required], + name: ['', notBlank], email: ['', [Validators.required, Validators.email]], - message: ['', Validators.required], + message: ['', notBlank], }); readonly submissionStatus = signal('idle'); + /** Errors wait until the field is touched, so nobody is told off before they've typed. */ + showError(field: keyof typeof this.form.controls): boolean { + const control = this.form.controls[field]; + return control.touched && control.invalid; + } + onSubmit() { - if (this.form.invalid) return; + if (this.form.invalid) { + // Show every error at once, then take the user to the first one. + this.form.markAllAsTouched(); + const firstInvalid = Object.entries(this.form.controls).find(([, control]) => control.invalid); + this.host.nativeElement.querySelector(`#contact-${firstInvalid?.[0]}`)?.focus(); + return; + } this.submissionStatus.set('pending'); diff --git a/src/app/shared/validators.spec.ts b/src/app/shared/validators.spec.ts index e3f2125..b950430 100644 --- a/src/app/shared/validators.spec.ts +++ b/src/app/shared/validators.spec.ts @@ -3,10 +3,10 @@ import { notBlank } from './validators'; describe('notBlank', () => { it.each(['', ' ', '\n\t '])('flags %j as blank', (value) => { - expect(notBlank(new FormControl(value))).toEqual({ blank: true }); + expect(notBlank(new FormControl(value, { nonNullable: true }))).toEqual({ blank: true }); }); it('passes text with something in it, even with spaces around', () => { - expect(notBlank(new FormControl(' hi '))).toBeNull(); + expect(notBlank(new FormControl(' hi ', { nonNullable: true }))).toBeNull(); }); }); diff --git a/src/app/shared/validators.ts b/src/app/shared/validators.ts new file mode 100644 index 0000000..817e582 --- /dev/null +++ b/src/app/shared/validators.ts @@ -0,0 +1,12 @@ +import { AbstractControl, ValidationErrors } from '@angular/forms'; + +// [ng-08 forms] A validator is a plain function: control in, errors or null +// out. Validators.required only rejects '' (and null), so " " passes it. +// That's how a contact message of nothing but spaces got through. +// +// Return a small object keyed by the error name. Templates check it with +// control.hasError('blank'), so the key is part of the API: name it for what +// is wrong, not for the validator. +export function notBlank(control: AbstractControl): ValidationErrors | null { + return control.value.trim() === '' ? { blank: true } : null; +} From 08ae613e466d190d8ce8b6e54dcc06ef6cfeb45a Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:21:42 -0500 Subject: [PATCH 3/4] Write lesson 08 with a group validator and FormArray demo --- .../lessons/lesson-08-forms.spec.ts | 2 +- .../lessons/lesson-08-forms.ts | 318 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 1 + src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 5 files changed, 332 insertions(+), 1 deletion(-) create mode 100644 src/app/thoughts-content/lessons/lesson-08-forms.ts diff --git a/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts b/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts index 5107238..9ab7c4e 100644 --- a/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts +++ b/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts @@ -58,7 +58,7 @@ describe('Lesson08Forms', () => { await click('#demo-add-link'); expect(rows()).toBe(2); - await click('.demo-link-row:last-child .demo-remove-link'); + await click('.demo-link-row:last-of-type .demo-remove-link'); expect(rows()).toBe(1); }); diff --git a/src/app/thoughts-content/lessons/lesson-08-forms.ts b/src/app/thoughts-content/lessons/lesson-08-forms.ts new file mode 100644 index 0000000..4800ece --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-08-forms.ts @@ -0,0 +1,318 @@ +import { Component, inject } from '@angular/core'; +import { FormBuilder, ReactiveFormsModule, ValidationErrors, ValidatorFn, Validators } from '@angular/forms'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; + +/** + * [ng-08 forms] A cross-field rule belongs on the group, not on either field: + * "confirm must equal password" is about both, and a validator on confirm + * alone wouldn't re-run when the password changes. + */ +const matchingPasswords: ValidatorFn = (group): ValidationErrors | null => { + const { password, confirm } = group.value as { password: string; confirm: string }; + return confirm && password !== confirm ? { mismatch: true } : null; +}; + +@Component({ + selector: 'app-lesson-08-forms', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions, ReactiveFormsModule], + template: ` + +

Simple

+

+ Angular has two form APIs. Template-driven forms put + ngModel on inputs and let the template build the model. They're fine for a + search box. Reactive forms build the model in TypeScript, as a tree of + FormGroup, FormControl and FormArray, and bind + inputs to it with formControlName. Most production apps use reactive forms: + the logic is testable without a DOM, and the types follow the model. +

+

+ This site's contact form is a reactive form. Writing this lesson, I found three things + wrong with it: +

+
    +
  • a message of only spaces passed Validators.required
  • +
  • Send was disabled with no explanation
  • +
  • its errors weren't connected to their fields for screen readers
  • +
+ + +

Intermediate

+

+ A validator is a function from a control to an errors object or + null. notBlank is three lines and now guards the name and + message. Cross-field rules go on the group. A + FormArray holds a list whose length changes at runtime. +

+ +
+
+ + +
+
+ + +
+ @if (showMismatch()) { +

Passwords don't match.

+ } + +
+

+ status: {{ form.status }} · dirty: {{ form.dirty }} · touched: + {{ form.touched }} +

+
{{ formValue() }}
+
+ + +

+ Typed forms. Since v14, the form's types are inferred from its initial + values. fb.nonNullable makes reset() go back to the initial value + instead of null, so form.value.name is string, not + string | null. +

+

+ Accessible errors. Show an error once the field is touched, not while + someone is still typing their first character. Tie it to the input with + aria-invalid and aria-describedby. Keep the submit button + enabled: on an invalid submit, markAllAsTouched() shows every error, then + focus moves to the first one. Put the result message in a live region that's always in + the DOM. +

+ +

Expert

+

+ Async validators run after the sync ones pass and put the control in + PENDING while they wait. They're the place for a "username taken" check. Pass + them separately, and set updateOn: 'blur' or debounce inside them, or every + keystroke is a request. +

+ +

+ ControlValueAccessor is how a custom component (a star + rating, a date picker) becomes a form control. It implements four methods, and then + formControlName works on it like on an input. +

+ + +

+ Signal Forms ship in Angular 21 as experimental + (@angular/forms/signals). The model is a plain signal you own, + form() wraps it in a tree of fields, and validation is a schema function. + Each field's value, validity and errors are signals, so no valueChanges + bridging is needed. I'd use it on a greenfield form and know reactive forms for every + existing codebase. Interviews will ask about both. +

+
+ + +

Pitfalls

+ +

+ Validators.required accepts whitespace. Add a + notBlank validator for text that has to say something. +

+
+ +

+ Disabled controls are left out of form.value. Use + getRawValue() when you need everything. +

+
+ +

+ setValue vs patchValue. + setValue throws unless you pass every field. patchValue takes a + subset, and silently ignores keys that don't exist, typos included. +

+
+ +

+ Mixing ngModel with formControlName on one + input. It's deprecated and the two models fight. Pick one API per form. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .demo-error { + margin: 0 0 8px; + font-size: 13px; + color: #ff6b6b; + } + .demo-links { + margin: 8px 0; + border: 1px dashed var(--border-primary, rgba(255, 255, 255, 0.3)); + border-radius: 8px; + } + .demo-value { + margin: 8px 0 0; + font-size: 12px; + white-space: pre-wrap; + } + `, +}) +export class Lesson08Forms { + private readonly fb = inject(FormBuilder); + + protected readonly form = this.fb.nonNullable.group( + { + password: ['', [Validators.required, Validators.minLength(8)]], + confirm: ['', Validators.required], + links: this.fb.nonNullable.array([this.link()]), + }, + { validators: matchingPasswords }, + ); + + protected showMismatch(): boolean { + return this.form.hasError('mismatch') && this.form.controls.confirm.touched; + } + + protected addLink(): void { + this.form.controls.links.push(this.link()); + } + + protected formValue(): string { + return JSON.stringify(this.form.getRawValue(), null, 2); + } + + private link() { + return this.fb.nonNullable.control('', Validators.pattern(/^(https:\/\/\S+)?$/)); + } + + protected readonly snippets = { + contact: `readonly form = this.fb.nonNullable.group({ + name: ['', notBlank], + email: ['', [Validators.required, Validators.email]], + message: ['', notBlank], +}); + +onSubmit() { + if (this.form.invalid) { + this.form.markAllAsTouched(); // show every error at once + // ...then focus the first invalid field + return; + } + // send +} + +`, + demo: `const matchingPasswords: ValidatorFn = (group) => { + const { password, confirm } = group.value; + return confirm && password !== confirm ? { mismatch: true } : null; +}; + +form = this.fb.nonNullable.group( + { + password: ['', [Validators.required, Validators.minLength(8)]], + confirm: ['', Validators.required], + links: this.fb.nonNullable.array([this.link()]), + }, + { validators: matchingPasswords }, // on the group: it reads both fields +); + +addLink() { this.form.controls.links.push(this.link()); } + +
+ @for (link of form.controls.links.controls; track link; let i = $index) { + + } +
`, + async: `const usernameFree = (users: UserService): AsyncValidatorFn => (control) => + timer(300).pipe( // debounce: resubscribed per value + switchMap(() => users.exists(control.value)), + map((taken) => (taken ? { taken: true } : null)), + ); + +username = new FormControl('', { + validators: [Validators.required], + asyncValidators: [usernameFree(inject(UserService))], + updateOn: 'blur', +});`, + cva: `@Component({ + selector: 'app-star-rating', + providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: StarRating, multi: true }], + ... +}) +export class StarRating implements ControlValueAccessor { + writeValue(value: number) { ... } // form → component + registerOnChange(fn: (value: number) => void) { this.onChange = fn; } // component → form + registerOnTouched(fn: () => void) { this.onTouched = fn; } + setDisabledState(disabled: boolean) { ... } +}`, + signalForms: `import { form, required, email, FormField } from '@angular/forms/signals'; + +readonly model = signal({ name: '', email: '' }); +readonly contact = form(this.model, (path) => { + required(path.name); + email(path.email); +}); + +contact.email().valid(); // a signal +contact.email().errors(); // a signal + +`, + }; + + protected readonly interview = [ + { + q: 'Reactive or template-driven forms?', + a: 'Template-driven forms build the model from ngModel in the template: quick for simple cases, but the logic is spread through HTML and hard to unit test. Reactive forms define the model in TypeScript, which makes them strongly typed, testable without a DOM, and better for dynamic fields, cross-field validation and complex flows. I default to reactive. In Angular 21, Signal Forms are an experimental third option built on signals.', + }, + { + q: 'How do you write a custom validator, and a cross-field one?', + a: 'A ValidatorFn takes a control and returns null when valid or an errors object like { blank: true }. For rules involving several fields, such as password confirmation or a date range, put the validator on the FormGroup so it sees every value and re-runs when any of them changes. Read it with group.hasError().', + }, + { + q: 'What does a ControlValueAccessor do?', + a: 'It is the bridge between a form control and a component or element. writeValue pushes the model into the view, registerOnChange and registerOnTouched give the component callbacks to report changes back, and setDisabledState handles disabling. Provide it with NG_VALUE_ACCESSOR as a multi provider, and formControlName and ngModel work on your component.', + }, + { + q: 'How do async validators work?', + a: 'They return an Observable or Promise of errors or null, and run only after the sync validators pass. While they run, the control status is PENDING. To avoid a request per keystroke, use updateOn: blur or debounce inside the validator with timer() and switchMap, since the validator is resubscribed on each value change.', + }, + { + q: 'How do you make a form accessible?', + a: 'Every input has a real label. Errors show once the field is touched, and are linked with aria-invalid and aria-describedby. The submit button stays enabled, and an invalid submit marks everything touched and focuses the first invalid field. Results go into a live region that already exists in the DOM. Use autocomplete attributes for personal data.', + }, + { + q: 'What changed with typed forms?', + a: 'Since Angular 14, FormControl, FormGroup and FormArray are generic and infer their types from initial values, so form.value.email is typed and typos are compile errors. nonNullable controls reset to their initial value instead of null, which removes string | null everywhere. UntypedFormGroup exists for migrating old code.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index 9885402..200f7a7 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -18,4 +18,5 @@ export const LESSON_PAGES: Record Promise>> = { '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), + 'angular-08-forms': () => import('./lesson-08-forms').then((m) => m.Lesson08Forms), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 948c46e..7992988 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -265,4 +265,7 @@ The second one was a real gap. The Projects app showed its error state on the fi '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.`, + 'angular-08-forms': `I opened the contact form to use as this lesson's example and found three things wrong with it. A message of nothing but spaces passed validation, because Validators.required only rejects an empty string. Send stayed greyed out until everything was valid, and nothing said why. And the error messages were just text sitting near the fields, with nothing telling a screen reader which field they belonged to. + +All three are fixed now. Send stays enabled; pressing it shows every problem and puts focus on the first one. The demo below covers what the contact form doesn't need: a rule that spans two fields, and a list of fields that grows and shrinks.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index f509e55..db542e0 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -251,4 +251,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'routing', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-08-forms', + title: 'Angular 08: Forms', + date: '2026-11-21', + summary: + 'Reactive forms, custom and cross-field validators, FormArray, accessible errors, ControlValueAccessor and the new Signal Forms. Built while fixing a contact form that accepted blank messages and never said what was wrong.', + tags: ['angular-guide', 'forms', 'angular'], + relatedApp: 'contact', + }, ]; From 6aa6f073ffd79a6b920e5a0f9a72c8ce6645f3fa Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:21:49 -0500 Subject: [PATCH 4/4] Bump to 1.4.7 with the lesson 08 changelog entry --- CHANGELOG.md | 8 ++++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b64e434..212c329 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.7 + +- **fix: the contact form accepted blank messages.** `Validators.required` only rejects an empty string, so a name or message of nothing but spaces got through. Both now use a small `notBlank` validator in `shared/validators.ts` +- **Send explains instead of greying out.** The button used to stay disabled until the form was valid, which can't be focused and says nothing about what's wrong. It's now enabled, except while a message is sending, so it can't double-submit. Pressing it on an invalid form shows every error and moves focus to the first field that needs fixing +- **Errors are tied to their fields.** Each error message has an id, and its input gets `aria-invalid` and `aria-describedby` while the error shows. The sending, sent and failed messages now live in one `role="status"` region that's always in the DOM, so they're announced. Name and email have `autocomplete` hints +- **Angular guide, lesson 08: forms** (`/thoughts/angular-08-forms`). The live demo is a password pair checked by a group-level validator, plus a `FormArray` of links you can add and remove, with the form's status and raw value shown as you type. The lesson covers async validators, `ControlValueAccessor`, and Angular 21's experimental Signal Forms, checked against the installed `@angular/forms` 21.2 +- Initial bundle 391.72 kB → 392.09 kB, the lesson's metadata. Forms code stays in lazy chunks + ## 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 diff --git a/package-lock.json b/package-lock.json index 511a96a..97c9914 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.6", + "version": "1.4.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.6", + "version": "1.4.7", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index 5990c57..ba9469d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.6", + "version": "1.4.7", "scripts": { "ng": "ng", "start": "ng serve",