Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "angular-paul",
"version": "1.4.6",
"version": "1.4.7",
"scripts": {
"ng": "ng",
"start": "ng serve",
Expand Down
71 changes: 57 additions & 14 deletions src/app/apps/contact-app.spec.ts
Original file line number Diff line number Diff line change
@@ -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<ContactApp>;
let component: ContactApp;
Expand All @@ -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', () => {
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -111,6 +151,9 @@ describe('ContactApp', () => {

const success = nativeEl.querySelector('.contact-success');
expect(success).toBeTruthy();
// 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 () => {
Expand Down
97 changes: 70 additions & 27 deletions src/app/apps/contact-app.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -12,20 +13,41 @@ type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error';
<h3>New Message</h3>
</div>

<form [formGroup]="form" (ngSubmit)="onSubmit()" class="contact-form">
<!-- [ng-08 forms] novalidate: Angular's validators are the single
source of truth, so the browser's own bubbles don't compete. -->
<form [formGroup]="form" (ngSubmit)="onSubmit()" class="contact-form" novalidate>
<!-- Each error is tied to its field: aria-invalid says "this is wrong",
aria-describedby points at the sentence that says why. Both are
only set while the error shows. -->
<div class="contact-field">
<label for="contact-name">Name</label>
<input id="contact-name" formControlName="name" placeholder="Your name" />
@if (form.controls.name.touched && form.controls.name.invalid) {
<span class="contact-error contact-error-name">Name is required</span>
<input
id="contact-name"
formControlName="name"
placeholder="Your name"
autocomplete="name"
[attr.aria-invalid]="showError('name') || null"
[attr.aria-describedby]="showError('name') ? 'contact-name-error' : null"
/>
@if (showError('name')) {
<span id="contact-name-error" class="contact-error contact-error-name">Name is required</span>
}
</div>

<div class="contact-field">
<label for="contact-email">Email</label>
<input id="contact-email" formControlName="email" placeholder="your@email.com" />
@if (form.controls.email.touched && form.controls.email.invalid) {
<span class="contact-error contact-error-email">Valid email is required</span>
<input
id="contact-email"
formControlName="email"
placeholder="your@email.com"
autocomplete="email"
[attr.aria-invalid]="showError('email') || null"
[attr.aria-describedby]="showError('email') ? 'contact-email-error' : null"
/>
@if (showError('email')) {
<span id="contact-email-error" class="contact-error contact-error-email"
>Valid email is required</span
>
}
</div>

Expand All @@ -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"
></textarea>
@if (form.controls.message.touched && form.controls.message.invalid) {
<span class="contact-error contact-error-message">Message is required</span>
@if (showError('message')) {
<span id="contact-message-error" class="contact-error contact-error-message"
>Message is required</span
>
}
</div>

<!-- Only disabled while sending, to stop a double submit. A button
disabled for being invalid can't be focused and explains nothing. -->
<div class="contact-actions">
<button
type="submit"
class="contact-submit"
[disabled]="form.invalid || submissionStatus() === 'pending'"
>
<button type="submit" class="contact-submit" [disabled]="submissionStatus() === 'pending'">
Send
</button>
</div>

@if (submissionStatus() === 'pending') {
<div class="contact-loading">Sending message...</div>
}
@if (submissionStatus() === 'success') {
<div class="contact-success">Message sent successfully!</div>
}
@if (submissionStatus() === 'error') {
<div class="contact-error-state">Failed to send message. Please try again.</div>
}
<!-- One live region that's always in the DOM. A region that appears
already holding its text often isn't announced at all. -->
<div role="status">
@if (submissionStatus() === 'pending') {
<div class="contact-loading">Sending message...</div>
}
@if (submissionStatus() === 'success') {
<div class="contact-success">Message sent successfully!</div>
}
@if (submissionStatus() === 'error') {
<div class="contact-error-state">Failed to send message. Please try again.</div>
}
</div>
</form>
</div>
`,
Expand Down Expand Up @@ -191,17 +219,32 @@ type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error';
})
export class ContactApp {
private readonly fb = inject(FormBuilder);
private readonly host = inject<ElementRef<HTMLElement>>(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<SubmissionStatus>('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<HTMLElement>(`#contact-${firstInvalid?.[0]}`)?.focus();
return;
}

this.submissionStatus.set('pending');

Expand Down
12 changes: 12 additions & 0 deletions src/app/shared/validators.spec.ts
Original file line number Diff line number Diff line change
@@ -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, { nonNullable: true }))).toEqual({ blank: true });
});

it('passes text with something in it, even with spaces around', () => {
expect(notBlank(new FormControl(' hi ', { nonNullable: true }))).toBeNull();
});
});
12 changes: 12 additions & 0 deletions src/app/shared/validators.ts
Original file line number Diff line number Diff line change
@@ -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<string>): ValidationErrors | null {
return control.value.trim() === '' ? { blank: true } : null;
}
68 changes: 68 additions & 0 deletions src/app/thoughts-content/lessons/lesson-08-forms.spec.ts
Original file line number Diff line number Diff line change
@@ -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<Lesson08Forms>;
let el: HTMLElement;

const text = (selector: string) => el.querySelector(selector)?.textContent ?? '';
const type = async (selector: string, value: string) => {
const input = el.querySelector<HTMLInputElement>(selector)!;
input.value = value;
input.dispatchEvent(new Event('input'));
input.dispatchEvent(new Event('blur'));
await fixture.whenStable();
};
const click = async (selector: string) => {
el.querySelector<HTMLButtonElement>(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-of-type .demo-remove-link');
expect(rows()).toBe(1);
});

it('has no axe violations', async () => {
expect(await axe(el)).toHaveNoViolations();
});
});
Loading
Loading