Sub topic 2
Validating Input with Built-in Validators
This chapter assumes you can already create a FormGroup and bind it with formGroup and formControlName. It also assumes you know standalone components and inject().
Built-in Validators
A validator is a function that checks a control's value and returns either an error object or null. The Validators class provides common ones: required, email, min, max, minLength, maxLength, and pattern. You pass them as the second item in a FormBuilder array, or in the validators option of a FormControl.
Status, Touched, and Dirty
Every control has a status: VALID, INVALID, PENDING, or DISABLED. A control is touched after the user leaves (blurs) the field, and dirty after the user changes its value. To avoid showing errors before the user has typed anything, check touched before you read hasError().
| Property | Becomes true when |
|---|---|
| `touched` | The field loses focus |
| `dirty` | The user changes the value |
| `invalid` | Any validator returns an error |
Typed Forms and FormBuilder
Reactive forms infer their types from initial values. By default, reset() sets a control back to null, so its type includes null. Non-nullable controls reset to their initial value instead. inject(FormBuilder).nonNullable makes every control non-nullable, which removes the need to repeat new FormControl(...) with options.
Nested Groups and FormArray
Use a nested group when related fields belong together, such as an address. Use a FormArray for a list whose length changes at runtime.
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-contact-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<input formControlName="email" />
@if (form.controls.email.touched && form.controls.email.hasError('email')) {
<p>Enter a valid email address.</p>
}
<div formGroupName="address">
<input formControlName="city" placeholder="City" />
</div>
<div formArrayName="phones">
@for (phone of phones.controls; track $index) {
<input [formControlName]="$index" />
}
</div>
<button type="button" (click)="addPhone()">Add phone</button>
</form>
`,
})
export class ContactFormComponent {
private fb = inject(FormBuilder).nonNullable;
form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
address: this.fb.group({ city: ['', Validators.required] }),
phones: this.fb.array([this.fb.control('', Validators.minLength(7))]),
});
get phones() {
return this.form.controls.phones;
}
addPhone(): void {
this.phones.push(this.fb.control('', Validators.minLength(7)));
}
}Exercise
After calling form.reset() on the component above, what is the value of form.controls.email, and why?
Show answer
It is '' (an empty string), because the control was created with the non-nullable FormBuilder, so reset() restores the initial value instead of setting it to null.