// create-account.component.ts import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-create-account', standalone: true, imports: [FormsModule], template: `
@if (username.invalid && username.touched) { @if (username.errors?.['required']) { Username is required. } @else if (username.errors?.['minlength']) { Username must be at least 3 characters. } }
@if (password.invalid && password.touched) { @if (password.errors?.['required']) { Password is required. } @else if (password.errors?.['minlength']) { Password must be at least 8 characters. } }
`, }) export class CreateAccountComponent { model = { username: '', password: '' }; onSubmit() { console.log(this.model); } } /* Notes: - control.errors is an object keyed by which validator failed — e.g. errors['required'] or errors['minlength'] — so checking each key shows the specific reason a field is invalid. - The optional chaining (errors?.['required']) guards against errors being null when the control is currently valid. - @if / @else if (Chapter 4) picks exactly one message, prioritizing "required" over "too short" when the field is empty. */