Sub topic 8
Adding tasks with a validated reactive form
This chapter adds the form that creates tasks. You will build TaskFormComponent around a single typed FormControl, attach validators, show errors at the right moment, and hand valid input to TaskService.
This chapter assumes you have these pieces from earlier chapters:
- The
Taskinterface and the signal-basedTaskServicewith itsadd()method. - Standalone components,
inject(), and template binding syntax. - Basic TypeScript, including generics and non-null types.
Why reactive forms
Angular has two form systems. Template-driven forms put the form model in the template through directives such as ngModel. Reactive forms create the model in the component class as plain objects (FormControl, FormGroup, FormArray), and the template binds to them.
For this app, reactive forms have three advantages:
- The validation rules live in TypeScript, where you can unit test them without rendering anything.
- The control is typed.
FormControl<string>gives you astringfrom.value, notany. - You can read and change the form state directly, for example with
reset()orsetValue().
A form with one text field does not need a FormGroup. A single FormControl is enough, and you can bind it with [formControl].
The control and its validators
A FormControl holds a value and tracks its state: validity, whether the user has touched it, and whether the value has changed. A validator is a function that receives the control and returns either null (valid) or an object of error flags (invalid).
Angular ships several built-in validators. Two are relevant here:
Validators.requiredfails when the value is an empty string,null, orundefined.Validators.maxLength(n)fails when the value is longer thanncharacters.
Here is the form component from the plan:
import { Component, inject } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-form',
imports: [ReactiveFormsModule],
template: `
<form (ngSubmit)="submit()">
<input [formControl]="title" placeholder="New task" />
<button type="submit" [disabled]="title.invalid">Add</button>
</form>
`,
})
export class TaskFormComponent {
private readonly service = inject(TaskService);
readonly title = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.maxLength(100)],
});
submit(): void {
const value = this.title.value.trim();
if (this.title.valid && value) {
this.service.add(value);
this.title.reset();
}
}
}Each part does a specific job:
imports: [ReactiveFormsModule]makes the[formControl]directive available. A standalone component only sees what it imports.nonNullable: truemakes the control's typeFormControl<string>and makesreset()return to the initial value''. Without it,reset()sets the value tonull, and the type isFormControl<string | null>.(ngSubmit)fires when the form is submitted, whether by clicking the submit button or by pressing Enter in the input. It also prevents the browser's default page reload.[disabled]="title.invalid"keeps the button inactive while a validator is failing.
What happens on submit
The following diagram shows the path from user input to the service.
Why submit() checks again
Disabling the button is a convenience, not a guarantee. Pressing Enter can still trigger ngSubmit in some situations, and code or tests can call submit() directly. The method therefore validates its own input, which is the rule to follow at any boundary where data enters your logic.
The check also covers a gap in the validators. Validators.required accepts " " because the string is not empty. The control would be valid, the button enabled, and without the trim() guard you would add a task whose title is invisible.
Rejecting whitespace-only input with a custom validator
The guard in submit() stops the bad task, but the user sees an enabled button that does nothing. A better fix is to make the control invalid. A custom validator is a function with the ValidatorFn type:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const notBlank: ValidatorFn = (
control: AbstractControl,
): ValidationErrors | null => {
const value = control.value;
return typeof value === 'string' && value.trim().length === 0
? { blank: true }
: null;
};Save it as not-blank.validator.ts and add it to the validators array:
validators: [Validators.required, notBlank, Validators.maxLength(100)],An empty string now produces two errors, required and blank. That is fine, because the template can choose which one to display. Keep the guard in submit() as well, because the validator does not trim the value that gets stored.
Note that maxLength(100) counts the untrimmed text. A title with 98 characters and 5 trailing spaces is rejected even though it would fit after trimming. For a task list this is acceptable. If it matters, write a validator that measures value.trim().length.
Showing error messages
A disabled button gives no explanation. Add messages below the input, and decide when to show them. An error shown while the field is still pristine (never edited) looks like a scolding on an empty form. The usual rule is to show errors after the user has interacted with the control, using the touched flag. A control becomes touched when it loses focus.
template: `
<form (ngSubmit)="submit()">
<input [formControl]="title" placeholder="New task" aria-describedby="title-error" />
<button type="submit" [disabled]="title.invalid">Add</button>
<div id="title-error" role="alert">
@if (title.touched && title.hasError('required')) {
<p>Enter a title.</p>
} @else if (title.touched && title.hasError('blank')) {
<p>The title cannot be only spaces.</p>
}
@if (title.hasError('maxlength')) {
<p>
Titles are limited to 100 characters
({{ title.getError('maxlength').actualLength }} entered).
</p>
}
</div>
</form>
`,Points worth noting:
hasError('name')checks for a specific error key.getError('name')returns the error's payload. Formaxlength, the payload is{ requiredLength, actualLength }.- The
maxlengthmessage does not wait fortouched. The user is typing at that moment and needs the feedback immediately. role="alert"on the container makes screen readers announce messages when they appear.reset()marks the control pristine and untouched. After a successful add, therequiredmessage does not appear even though the empty value is invalid.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| Console error: "Can't bind to 'formControl' since it isn't a known property of 'input'" | `ReactiveFormsModule` is missing from the component's `imports` | Add it to the `imports` array | |
| After submit, the input shows `null` or the type is `string \ | null` | The control was created without `nonNullable: true` | Pass `{ nonNullable: true }` as an option |
| Page reloads on submit | The `<form>` has no `(ngSubmit)` handler and the button is `type="submit"` | Bind `(ngSubmit)`, or handle the event yourself and call `preventDefault()` | |
| Whitespace-only titles are accepted | `required` only rejects empty values | Add a `notBlank` validator and trim before saving | |
| Error message flashes right after adding a task | The message does not check `touched`, or the control was not reset | Gate it on `touched` and call `reset()` after saving | |
| The button never enables | A validator is returning errors you did not expect | Log `title.errors` to see the active error keys |
Testing the form
Because the logic is in the class, you can test it without clicking anything. TestBed.createComponent works for a standalone component with no extra setup:
import { TestBed } from '@angular/core/testing';
import { TaskFormComponent } from './task-form.component';
import { TaskService } from './task.service';
describe('TaskFormComponent', () => {
it('adds a trimmed task and resets the control', () => {
const fixture = TestBed.createComponent(TaskFormComponent);
const component = fixture.componentInstance;
const service = TestBed.inject(TaskService);
component.title.setValue(' Buy milk ');
component.submit();
expect(service.tasks().map(t => t.title)).toEqual(['Buy milk']);
expect(component.title.value).toBe('');
});
it('does not add a task when the title is empty', () => {
const fixture = TestBed.createComponent(TaskFormComponent);
const service = TestBed.inject(TaskService);
fixture.componentInstance.submit();
expect(service.tasks()).toEqual([]);
});
});TaskService is provided in root, so TestBed.inject returns the same instance the component receives. Each test gets a fresh TestBed, so the second test starts with an empty list.
Where the form fits in the app
The form never touches the task list. It writes to TaskService, and the list component reads the service's tasks signal. When add() runs, the signal updates, and the list re-renders without any event passing between the two components. This is why the previous chapter put the state in a service: sibling components can stay unaware of each other.
Exercise
A user types three spaces into the input and presses Enter. Using only Validators.required and Validators.maxLength(100), what happens in the component above, and what is the minimal change that makes the control itself report the problem?
Show answer
required passes because the string " " is not empty, so the control is valid and ngSubmit fires. submit() trims the value to '', the value check fails, and nothing is added. The user gets no feedback. To make the control invalid, add a custom validator such as notBlank that returns { blank: true } when value.trim().length === 0, and include it in the validators array. The template can then show a message for the blank error.
Exercise
You remove nonNullable: true from the FormControl and keep the rest of the code the same. Name two things that change.
Show answer
The control's type becomes FormControl<string | null>, so this.title.value.trim() no longer compiles under strict null checks. Also, reset() sets the value to null instead of '', so the input is cleared but the value is no longer an empty string.