Sub topic 8
Adding tasks with a validated reactive form
This chapter assumes you have the TaskService from the previous chapter and know standalone components, inject(), and the @if control flow block. You will build a form that adds tasks and blocks invalid input.
Why reactive forms
Angular has two form styles. Template-driven forms keep state in the template. Reactive forms keep it in TypeScript objects you create yourself. Reactive forms are easier to test and to type, so this app uses them.
Three classes do the work:
FormControlholds one value and its validation state.FormGroupcollects named controls into one unit.Validatorsprovides rule functions such asrequiredandmaxLength.
Building the form
import { Component, inject } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-form',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<input formControlName="title" placeholder="New task" />
<button type="submit" [disabled]="form.invalid">Add</button>
@if (form.controls.title.hasError('maxlength')) {
<p role="alert">Titles can have at most 100 characters.</p>
}
</form>
`,
})
export class TaskFormComponent {
private readonly service = inject(TaskService);
readonly form = new FormGroup({
title: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.maxLength(100)],
}),
});
submit(): void {
const control = this.form.controls.title;
const value = control.value.trim();
if (control.valid && value) {
this.service.add(value);
this.form.reset();
}
}
}How it works
The component imports ReactiveFormsModule, which supplies the formGroup and formControlName directives. The FormGroupDirective on the <form> also emits ngSubmit and cancels the browser's own submit, so the page does not reload.
The option nonNullable: true matters for typing. Without it, value has the type string | null, and reset() sets the control to null. With it, value is always a string, and reset() restores the initial value ''.
Validators run every time the value changes. The group's invalid property is true while any control fails, so [disabled]="form.invalid" keeps the button off for an empty title. The ngSubmit handler still re-checks validity, because a user can press Enter in some situations where the button state lags behind.
Common errors
- Forgetting the import. Without
ReactiveFormsModuleinimports, Angular reports thatformGroupis not a known property. - Accepting whitespace.
Validators.requiredtreats" "as non-empty. That is whysubmit()trims the value and checks it again. - Typing
nullby accident. Leaving outnonNullable: trueforces you to handlenulleverywhere the value is used. - Wrong directive pairing.
formControlNameworks only inside aformGroup. Outside a group, use[formControl]instead.
Try it
Add <app-task-form /> to the app component's template and list it in imports. Type a title and press Enter. The task appears in the list and the input clears. Then clear the input and check that the button is disabled.
Exercise
Why does submit() call trim() and re-check valid even though the button is disabled when the form is invalid?
Show answer
Validators.required accepts a title made only of spaces, so the form can be valid while the trimmed title is empty. The extra check stops such a task from being added. It also covers a submit that happens by a route other than the disabled button, such as pressing Enter.