Blog

Part 21 · Signal Forms in Angular: form(), [formField] and Validation

Signal Forms keep a form’s data in one signal and tie each input to it with [formField]. This part covers form(), the field tree, field state, built-in validators, and showing errors at the right time.

Almost every app has a form somewhere: sign up, check out, edit a profile. A form has to keep the data and the inputs in step, check what the user typed, and say what’s wrong at a moment that doesn’t annoy them. Angular 22 does this with Signal Forms, from @angular/forms/signals.

This part covers a form’s data as a signal, form(), binding inputs with [formField], the field tree, the state each field keeps (valid, touched, dirty and more), the built-in validators, and showing errors only after the user has left a field. It builds on signals from Part 3 and the event bindings from Part 2. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

Paste this into src/app/app.ts:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Name <input [formField]="helloForm.name" /></label>
    <p>Hello, {{ hello().name }}</p>
    <button (click)="hello.set({ name: 'Ben' })">Use Ben</button>
  `,
})
export class App {
  protected readonly hello = signal({ name: '' });
  protected readonly helloForm = form(this.hello);
}

There’s no (input) handler anywhere, and the button never touches the input. Before you read on, guess. Type Ana in the box. What does the line under it say? Then click Use Ben. What’s in the box now?

Type Ana, and the page shows:

Name
Hello, Ana
Use Ben

The text you typed went into the hello signal, and the template read it from there. Now click Use Ben. The page shows:

Name
Hello, Ben
Use Ben

The box says Ben too. Click at the end of it and press Backspace once, and the line reads Hello, Be:

Name
Hello, Be
Use Ben

So the data goes both ways. Typing changes the signal, and changing the signal changes the box. (The page text doesn’t include what’s inside an input box, which is why the box’s value doesn’t appear in the text above.)

Three pieces: a model, a form and a field

That small page has all three parts of Signal Forms.

The model is an ordinary writable signal that holds the form’s data: signal({ name: '' }). Angular’s docs call it the form’s model. It has nothing to do with model() from Part 6; here “model” just means “the data”. You choose its shape. Each property becomes one field.

The form comes from form(this.hello). You pass it the model signal, and it gives back a field tree: an object with one field for each property of the model. helloForm.name is the field for name. The form doesn’t keep its own copy of the data. It reads from the model and writes to it.

The binding is [formField]="helloForm.name" on the input. FormField is a directive (a class that adds behaviour to an element; Part 11 covers them). It puts the field’s value into the input, and when you type, it writes the new value back into the model. That’s why FormField is in the component’s imports, like any other directive.

The two imports come from @angular/forms/signals. The package @angular/forms is already in a project made by ng new, so there’s nothing to install.

The field tree

A field tree has the same shape as the model. If the model has a nested object, the tree has a nested field:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Name <input [formField]="signupForm.name" /></label>
    <label>City <input [formField]="signupForm.address.city" /></label>
    @let name = signupForm.name();
    <p>name: "{{ name.value() }}", touched {{ name.touched() }}, dirty {{ name.dirty() }}</p>
    <p>form: touched {{ signupForm().touched() }}, dirty {{ signupForm().dirty() }}</p>
    <p>Model: {{ signup().name }} from {{ signup().address.city }}</p>
    <button (click)="signupForm.address.city().value.set('Lima')">Lima</button>
  `,
})
export class App {
  protected readonly signup = signal({ name: '', address: { city: '' } });
  protected readonly signupForm = form(this.signup);
}

signupForm.address.city is the field for signup().address.city. You reach it with the same dots you’d use on the data. TypeScript knows the shape too, so a typo like signupForm.adress won’t build.

A field is also a function. Call it to get the field’s state: signupForm.name(). The state is an object full of signals about that field. name.value() is its value, name.touched() and name.dirty() are two more we’ll meet in a moment. @let (from Part 4) saves signupForm.name() under a short name for the rest of the template.

The root has state too: signupForm() is the state of the whole form.

When the page loads, it shows:

Name City
name: "", touched false, dirty false
form: touched false, dirty false
Model: from
Lima

The empty name: "" is the value, an empty string. (Name City is the two labels, which sit on one line, so the page text runs them together.)

touched and dirty

Type Ana in Name. The page shows:

Name City
name: "Ana", touched false, dirty true
form: touched false, dirty true
Model: Ana from
Lima

dirty means the user changed the value. touched means the user has been in the field and left it. You’re still in the box, so it isn’t touched yet. Press Tab to move to City, and the page shows:

Name City
name: "Ana", touched true, dirty true
form: touched true, dirty true
Model: Ana from
Lima

Leaving a field is called a blur. [formField] listens for it and marks the field touched. The form’s root is touched and dirty as soon as any field inside it is.

Now click Lima. The handler writes to the city field’s value, which is a writable signal:

Name City
name: "Ana", touched true, dirty true
form: touched true, dirty true
Model: Ana from Lima
Lima

The model changed, because writing to a field writes to the model. And the city box shows Lima. You could write this.signup.update(...) instead; it’s the same data.

The picture so far

Here’s the field tree for a smaller sign-up form: a name, an email and an address with a city.

model signal field tree inputs signup name: 'Ana' email: '' address: { city: '' } schema required(path.name) email(path.email) required(path.address.city) form() adds the rules signupForm .name .email .address .city Name: Ana Email: a group: no input City: signupForm.name() is the field's state, and every part of it is a signal: value() 'Ana', valid() true, errors() [], touched() true, dirty() true value into the input reads a signal typing writes back

The form doesn’t copy the data. Each field reads and writes its own part of the model signal, and [formField] ties it to one input.

Field state at a glance

Every field state has these signals. You call each one to read it.

Signal What it says
value() The field’s value. value is a writable signal, so value.set(x) works too.
valid() / invalid() Whether the field (and anything inside it) passes its rules.
errors() A list of what’s wrong with this field, one object per broken rule.
touched() The user has left the field at least once.
dirty() The user has changed the value. A change from code doesn’t count.
disabled() / readonly() / hidden() Whether the field is switched off, can’t be edited, or shouldn’t be shown.
required() Whether a required rule applies right now.

valid() and invalid() aren’t always opposites. Part 22 covers checks that wait for a server; while one is still running, the field is neither valid nor invalid yet. With the rules in this part, they’re always opposites.

Numbers, checkboxes and dropdowns

The model decides what type each value has. A number in the model needs an <input type="number">, and it stays a number. A boolean goes with a checkbox. A dropdown (<select>) gives a string.

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Quantity <input type="number" [formField]="orderForm.quantity" /></label>
    <label>Gift wrap <input type="checkbox" [formField]="orderForm.giftWrap" /></label>
    <label>
      Size
      <select [formField]="orderForm.size">
        <option value="s">Small</option>
        <option value="l">Large</option>
      </select>
    </label>
    @let o = order();
    <p>Quantity plus one: {{ o.quantity + 1 }}. Gift wrap: {{ o.giftWrap }}. Size: {{ o.size }}</p>
  `,
})
export class App {
  protected readonly order = signal({ quantity: 1, giftWrap: false, size: 's' });
  protected readonly orderForm = form(this.order);
}

Type 20 in Quantity, tick Gift wrap and choose Large. The page shows:

Quantity Gift wrap Size
Small
Large
Quantity plus one: 21. Gift wrap: true. Size: l

quantity + 1 is 21, not "201". The input put a real number in the model. (Small and Large show up in the page text because they’re the dropdown’s options.)

Now clear the Quantity box. The page shows:

Quantity Gift wrap Size
Small
Large
Quantity plus one: 1. Gift wrap: true. Size: l

An empty number box gives null, and null + 1 is 1 in JavaScript. If a number field can be empty, give it the type number | null in the model and handle null where you use it.

Rules: the schema

So far nothing checks what the user types. Rules go in a second argument to form(), called the schema. It’s a function. Angular calls it once, with a path for each field, and you call rule functions on those paths:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form, minLength, required } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Name <input [formField]="signupForm.name" /></label>
    @let name = signupForm.name();
    <p>valid {{ name.valid() }}, errors: {{ kinds() }}</p>
  `,
})
export class App {
  protected readonly signup = signal({ name: '' });
  protected readonly signupForm = form(this.signup, (path) => {
    required(path.name);
    minLength(path.name, 2);
  });

  protected kinds() {
    return this.signupForm
      .name()
      .errors()
      .map((error) => error.kind)
      .join(', ');
  }
}

path.name looks like signupForm.name, but it isn’t a field. It names where a rule goes. The schema runs once, when the form is made; the rules then run by themselves every time the value changes, like a computed.

errors() is a list of error objects. Each has a kind: a short name for the broken rule. kinds() joins them into text. When the page loads, it shows:

Name
valid false, errors: required

Only required, even though an empty string is shorter than 2. The length rules skip empty values, so “you didn’t fill this in” and “this is too short” never show up at once. Type A:

Name
valid false, errors: minLength

Now it’s minLength. Type Al, and the errors are gone:

Name
valid true, errors:

The rules also show up in the HTML. Angular adds required and minlength to the input, so screen readers can tell the user what’s expected. The input now looks like this:

<input minlength="2" name="ng.form0.name" required="" />

(The name attribute is one Angular makes up for each field.)

The built-in rules

All of these are imported from @angular/forms/signals:

Rule Checks Works on
required(path) there’s a value (a checkbox must be ticked) anything
email(path) looks like an email address strings
minLength(path, n) / maxLength(path, n) at least / at most n characters strings (and lists)
min(path, n) / max(path, n) at least / at most n numbers
pattern(path, /regex/) matches a regular expression strings

email, the length rules, min, max and pattern all skip an empty value. Pair them with required when the field must be filled in.

email only checks the rough shape. In the worked example below, ana@ fails it, but ana@example passes, with no dot after the @. Only sending an email proves an address is real.

The rules are typed. min on a string field won’t build, and neither will email on a number.

Messages

An error’s kind is for your code. For the user, you want a sentence. Each rule takes an options object as its last argument, with a message:

required(path.email, { message: 'Enter your email' });
email(path.email, { message: "That doesn't look like an email address" });

Without a message, the error’s message is undefined. Angular doesn’t write messages for you. The next example uses messages, and shows them at the right time.

Showing errors after the user leaves the field

If a form shouts “Name is required” before you’ve typed anything, it feels like a telling-off. The usual answer is to wait until the field is touched:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, email, form, required } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Email <input type="email" [formField]="signupForm.email" /></label>
    @let field = signupForm.email();
    @if (field.touched() && field.invalid()) {
      @for (error of field.errors(); track error.kind) {
        <p class="error">{{ error.message }}</p>
      }
    }
    <label>Name <input [formField]="signupForm.name" /></label>
  `,
  styles: `
    .error {
      color: #b00020;
    }
  `,
})
export class App {
  protected readonly signup = signal({ email: '', name: '' });
  protected readonly signupForm = form(this.signup, (path) => {
    required(path.email, { message: 'Enter your email' });
    email(path.email, { message: "That doesn't look like an email address" });
  });
}

@for loops over the field’s errors. track error.kind works as a key here because the two rules have different kinds.

When the page loads, the email is empty and invalid, but nothing is shown. Type ana@ in Email. Still nothing, because you’re still in the box:

Email Name

Press Tab to move to Name. The field is touched now, and the page shows:

Email
That doesn't look like an email address
Name

Go back and finish the address: type ana@example.com in Email. The message goes away while you type, because invalid() turned false:

Email Name

That’s the pattern most forms want: quiet until you leave a field, then live feedback while you fix it. A field the user never visits is never touched, so its errors never show. Part 22 covers submit, which marks every field touched when the user tries to send the form.

disabled, readonly and hidden

Some rules don’t check the value. They change how a field behaves. Each takes a when function that works like a computed: it can read other fields, and the rule follows them.

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, disabled, form, hidden } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Gift <input type="checkbox" [formField]="orderForm.gift" /></label>
    @if (!orderForm.giftNote().hidden()) {
      <label>Gift note <input [formField]="orderForm.giftNote" /></label>
    }
    <label>Coupon <input [formField]="orderForm.coupon" /></label>
    <p>Coupon disabled: {{ orderForm.coupon().disabled() }}</p>
  `,
})
export class App {
  protected readonly order = signal({ gift: false, giftNote: '', coupon: '' });
  protected readonly orderForm = form(this.order, (path) => {
    hidden(path.giftNote, { when: ({ valueOf }) => !valueOf(path.gift) });
    disabled(path.coupon, { when: ({ valueOf }) => valueOf(path.gift) });
  });
}

when gets an object with helpers in it. { valueOf } picks one of them out (that’s JavaScript destructuring), and valueOf(path.gift) reads the current value of another field.

When the page loads, the gift note is hidden:

Gift Coupon
Coupon disabled: false

Tick Gift, and the page shows:

Gift Gift note Coupon
Coupon disabled: true

The Gift note box appeared, and Coupon is greyed out. Angular put the disabled attribute on that input for you:

  • disabled puts disabled on the input. The user can’t change it, and its rules stop counting: a disabled field never makes the form invalid.
  • readonly puts readonly on the input. The user can’t change it, and, as with disabled, its rules stop counting.
  • hidden does not hide anything on the page. It only marks the field as hidden, and its rules stop counting. Its value stays in the model. You remove it yourself, with @if (!field().hidden()). If you leave a hidden field on the page, Angular warns in the console with NG01916: Field '...' is hidden but is being rendered. Hidden fields should be removed from the DOM using @if.

Because [formField] sets these for you, you can’t set them yourself. <input [formField]="..." disabled /> won’t build: NG8022: Setting the 'disabled' attribute is not allowed on nodes using the '[formField]' directive. The same goes for [value]. Use a rule instead.

Worked example: a sign-up form

Now let’s put it together: name, email, age, and a nested address. Each field shows its own errors after it’s touched, and a line at the bottom says whether the whole form is ready. Sending it is Part 22’s job.

// src/app/app.ts
import { Component, signal } from '@angular/core';
import {
  FormField,
  email,
  form,
  max,
  maxLength,
  min,
  pattern,
  required,
} from '@angular/forms/signals';

interface Signup {
  name: string;
  email: string;
  age: number | null;
  address: { city: string; postcode: string };
}

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Name <input [formField]="signupForm.name" /></label>
    @let name = signupForm.name();
    @if (name.touched() && name.invalid()) {
      <p>{{ name.errors()[0].message }}</p>
    }
    <label>Email <input type="email" [formField]="signupForm.email" /></label>
    @let mail = signupForm.email();
    @if (mail.touched() && mail.invalid()) {
      <p>{{ mail.errors()[0].message }}</p>
    }
    <label>Age <input type="number" [formField]="signupForm.age" /></label>
    @let age = signupForm.age();
    @if (age.touched() && age.invalid()) {
      <p>{{ age.errors()[0].message }}</p>
    }
    <label>City <input [formField]="signupForm.address.city" /></label>
    <label>Postcode <input [formField]="signupForm.address.postcode" /></label>
    @let postcode = signupForm.address.postcode();
    @if (postcode.touched() && postcode.invalid()) {
      <p>{{ postcode.errors()[0].message }}</p>
    }
    <p>{{ signupForm().valid() ? 'Ready to send' : 'Not ready yet' }}</p>
  `,
})
export class App {
  protected readonly signup = signal<Signup>({
    name: '',
    email: '',
    age: null,
    address: { city: '', postcode: '' },
  });
  protected readonly signupForm = form(this.signup, (path) => {
    required(path.name, { message: 'Enter your name' });
    maxLength(path.name, 40, { message: 'Keep it under 40 characters' });
    required(path.email, { message: 'Enter your email' });
    email(path.email, { message: "That doesn't look like an email address" });
    required(path.age, { message: 'Enter your age' });
    min(path.age, 13, { message: 'You must be 13 or older' });
    max(path.age, 120, { message: 'Check your age' });
    required(path.address.city);
    pattern(path.address.postcode, /^\d{5}$/, { message: 'Use 5 digits' });
  });
}

Some things to notice:

  • interface Signup describes the model, and signal<Signup>(...) uses it. age starts as null, so the box starts empty instead of showing 0.
  • Each field shows only its first error, errors()[0]. That’s usually enough for the user, and the @if makes sure there is one.
  • The rules for address.city and address.postcode reach into the nested object with dots, the same way the template does.
  • city has required but no message and no error line. It still counts: the form isn’t valid while it’s empty.
  • signupForm().valid() is true only when every field inside it is valid.

Fill it in. Type Ana for the name, ana@ for the email, 9 for the age, Lima for the city and 123 for the postcode, then press Tab. The page shows:

Name Email
That doesn't look like an email address
Age
You must be 13 or older
City Postcode
Use 5 digits
Not ready yet

Now fix the three: type ana@example.com, 19 and 15001. The page shows:

Name Email Age City Postcode
Ready to send

Every message is gone, and the form is ready.

Worked example: reading two build errors

Here’s the first try at a small form for a book’s page count. It has two mistakes.

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  template: `<label>Pages <input [formField]="bookForm.pages" /></label>`,
})
export class App {
  protected readonly book = signal({ pages: 100 });
  protected readonly bookForm = form(this.book);
}

ng serve stops with:

✘ [ERROR] NG8002: Can't bind to 'formField' since it isn't a known property of 'input'. Find more at https://next.angular.dev/errors/NG8002 [plugin angular-compiler]

    src/app/app.ts:7:33:
      7 │ ...ate: `<label>Pages <input [formField]="bookForm.pages" /></label>`,
        ╵                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Read it piece by piece:

  • NG8002 is Angular’s code for “a binding on an element that doesn’t have that property”.
  • Can't bind to 'formField' since it isn't a known property of 'input' means the compiler looked for something called formField on an <input> and found nothing. The [formField] attribute only means something when the FormField directive is in the component’s imports. Without it, Angular treats formField as a property of the input element, and inputs don’t have one.

Add the import, and the directive to imports:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `<label>Pages <input [formField]="bookForm.pages" /></label>`,
})
export class App {
  protected readonly book = signal({ pages: 100 });
  protected readonly bookForm = form(this.book);
}

Now the second mistake shows up:

✘ [ERROR] TS2322: Type 'WritableSignal<number>' is not assignable to type '{ (): string; set: (v: string) => void; } | { (): number | null; set: (v: number | null) => void; }'.
  Type 'WritableSignal<number>' is not assignable to type '{ (): string; set: (v: string) => void; }'.
    Types of property 'set' are incompatible.
      Type '(value: number) => void' is not assignable to type '(v: string) => void'.
        Types of parameters 'value' and 'v' are incompatible.
          Type 'string' is not assignable to type 'number'. [plugin angular-compiler]

    src/app/app.ts:8:46:
      8 │ ...ate: `<label>Pages <input [formField]="bookForm.pages" /></label>`,
        ╵                                           ~~~~~~~~~~~~~~

This one is longer, but it says something useful:

  • TS2322 is TypeScript’s “this type doesn’t fit there”.
  • WritableSignal<number> is the type of the field’s value: pages is a number.
  • The type after “not assignable to type” lists what a plain <input> can hold: a string, or a number | null. Our pages is a number with no null, so it fits neither. A number box, <input type="number">, also accepts a plain number.

A page count is a number, and the user should type digits, so the fix is a number box:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Pages <input type="number" [formField]="bookForm.pages" /></label>
    <p>{{ book().pages }} pages</p>
  `,
})
export class App {
  protected readonly book = signal({ pages: 100 });
  protected readonly bookForm = form(this.book);
}

Type 250, and the page shows:

Pages
250 pages

That check happened when you built the app, not when a user typed. Signal Forms checks the type of every [formField] binding against the input it’s on.

In older code

Before Signal Forms, Angular had two other ways to build forms, and you’ll see both in existing projects. Reactive forms build the form in the class out of FormGroup and FormControl objects, and bind it with [formGroup] and formControlName; Part 23 covers them. Template-driven forms use [(ngModel)] on each input and FormsModule in imports. Both keep their own copy of the data inside the form, where Signal Forms keeps it in your model signal.

Best practices

  • Keep the form’s data in one model signal, and build the form from it. The model is the single place the data lives, so code that reads it never disagrees with the inputs. It replaces copying values out of inputs in (input) handlers.
  • Match the input to the model’s type. <input type="number"> for numbers, a checkbox for booleans, and number | null when a number can be empty. The build then checks every binding, instead of a string sneaking into a number.
  • Put rules in the schema, with a message for each one the user can see. The schema is one place to read every rule. It replaces if checks scattered through click handlers, and hand-written required and minlength attributes.
  • Show errors after touched(), not on page load. The user gets feedback once they’ve had a go. It replaces showing every error from the start, or only on send.
  • Use disabled, readonly and hidden rules, not attributes. The rule keeps the attribute, the field’s state and validity in step. It replaces [disabled] bindings, which [formField] doesn’t allow anyway.

Tips and traps

  • Forgetting imports: [FormField]. The build fails with NG8002, Can't bind to 'formField' since it isn't a known property of 'input'. Import FormField from @angular/forms/signals and add it to imports.
  • Calling the field in the binding. [formField]="signupForm.name()" fails with TS2322, Type 'FieldState<string, string>' is not assignable to type 'Field<any, string | number>'. The binding wants the field itself, without (). You call it only to read state.
  • Expecting a default message. error.message is undefined unless you gave the rule a message. Show error.kind while you build, and add messages before you ship.
  • minLength or email alone on a field that must be filled in. They skip empty values, so an empty field passes. Add required.
  • A hidden field still on the page. hidden doesn’t remove anything, and the console warns NG01916: Field '...' is hidden but is being rendered. Wrap the input in @if (!field().hidden()).
  • Errors that never appear. A field is touched only after the user leaves it. A field they never visit stays untouched, so its errors stay quiet. That’s on purpose; Part 22’s submit marks every field touched.

The model signal holds the data, the field tree mirrors its shape, and [formField] keeps each input and its field in step both ways.

Exercises

Exercise 1. Add a phone field to this form. It must be filled in and be exactly 10 digits. Show “Enter a 10-digit phone number” after the user leaves the field, if it’s wrong.

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form, required } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `<label>Name <input [formField]="contactForm.name" /></label>`,
})
export class App {
  protected readonly contact = signal({ name: '' });
  protected readonly contactForm = form(this.contact, (path) => {
    required(path.name);
  });
}

Exercise 2. This form shows “Enter a username” as soon as the page loads. Change it so the message appears only after the user has left the field.

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form, required } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Username <input [formField]="loginForm.username" /></label>
    @if (loginForm.username().invalid()) {
      <p>Enter a username</p>
    }
  `,
})
export class App {
  protected readonly login = signal({ username: '' });
  protected readonly loginForm = form(this.login, (path) => {
    required(path.username);
  });
}
Username
Enter a username

Exercise 3. A newsletter form has a Send me news checkbox and an Email field. The email should be required only while the box is ticked. Hint: required takes a when function, like hidden and disabled. Show valid or invalid for the whole form so you can see it change.

Answers

1. Add phone to the model, a required and a pattern rule with the same message, and an input with its own error line:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form, pattern, required } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Name <input [formField]="contactForm.name" /></label>
    <label>Phone <input type="tel" [formField]="contactForm.phone" /></label>
    @let phone = contactForm.phone();
    @if (phone.touched() && phone.invalid()) {
      <p>{{ phone.errors()[0].message }}</p>
    }
  `,
})
export class App {
  protected readonly contact = signal({ name: '', phone: '' });
  protected readonly contactForm = form(this.contact, (path) => {
    required(path.name);
    const message = 'Enter a 10-digit phone number';
    required(path.phone, { message });
    pattern(path.phone, /^\d{10}$/, { message });
  });
}

Type 12345 in Phone and press Tab. The page shows:

Name Phone
Enter a 10-digit phone number

Type 0123456789, and the message goes away:

Name Phone

2. Check touched() as well as invalid():

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, form, required } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Username <input [formField]="loginForm.username" /></label>
    @let username = loginForm.username();
    @if (username.touched() && username.invalid()) {
      <p>Enter a username</p>
    }
  `,
})
export class App {
  protected readonly login = signal({ username: '' });
  protected readonly loginForm = form(this.login, (path) => {
    required(path.username);
  });
}

When the page loads, it shows only the label:

Username

Click in Username and press Tab without typing. The page shows:

Username
Enter a username

3. when reads the checkbox with valueOf:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { FormField, email, form, required } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  template: `
    <label>Send me news <input type="checkbox" [formField]="newsForm.wantsNews" /></label>
    <label>Email <input type="email" [formField]="newsForm.email" /></label>
    <p>Form: {{ newsForm().valid() ? 'valid' : 'invalid' }}</p>
  `,
})
export class App {
  protected readonly news = signal({ wantsNews: false, email: '' });
  protected readonly newsForm = form(this.news, (path) => {
    required(path.email, { when: ({ valueOf }) => valueOf(path.wantsNews) });
    email(path.email);
  });
}

When the page loads, the box isn’t ticked, and an empty email is fine:

Send me news Email
Form: valid

Tick Send me news. The page shows:

Send me news Email
Form: invalid

Type ana@example.com in Email, and it’s valid again:

Send me news Email
Form: valid

What’s next

Our forms check what the user types, but they never send anything, and every rule is a built-in one. In Part 22, we’ll write our own rules, check a value against a server while the user waits, build a list of fields the user can add to, and submit the form.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.