AI Hints
Home›Angular Tutorial›FormGroup, Validators and Showing Errors
Angular · Lesson 87 of 120

Showing Errors

Friendly messages.

⏱ 2 min read▶ Video at 1:44:09🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Error objects are for code, not for people. Users need friendly messages, at the right moment. Not before they've even started typing.

  • Errors are for code
  • People need messages
  • At the right moment

When to show errors

Has error checks for one rule, by name. Touched becomes true, when the user leaves the field. So we show a message only when the field is touched, and has an error. Angular also adds classes, like ng invalid, and ng touched, for styling.

keyvalue
hasError('required')check one rule
touchedthe user left the field
Show whentouched and has an error
.ng-invalid.ng-touchedstyle with CSS

Friendly messages

Each message has its own if block. It shows only when the field is touched, and has that error. The CSS turns the border red, for touched, invalid inputs. We type sam, and press tab to leave the field. Run it. The email message appears, the border is red, and subscribe is disabled.

app.tstypescript
import { Component } from '@angular/core';
import { ReactiveFormsModule, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule],
  template: `
    <input [formControl]="email" placeholder="Email">
    @if (email.touched && email.hasError('required')) {
      <p class="error">Email is required.</p>
    }
    @if (email.touched && email.hasError('email')) {
      <p class="error">That doesn't look like an email.</p>
    }
    <button [disabled]="email.invalid">Subscribe</button>
  `,
  styles: `input.ng-invalid.ng-touched { border-color: crimson; }`,
})
export class App { email = new FormControl('', [Validators.required, Validators.email]); }
Also uses actions.json
[{"type": "input", "text": "sam"}, {"key": "Tab"}]

Summary

Use has error, and touched, to show friendly messages at the right time, and style invalid fields with CSS. Next, signal forms.

Key takeaways
  • hasError()
  • touched
  • ng-invalid
Next up: Signal Forms — forms from a signal