Sub topic 8
Submit the form
This chapter covers how to send a Signal Forms form to a server. It assumes you can build a form with form(), bind fields with [field], read field state as signals, and add built-in validators. Signal Forms is experimental in Angular 21, so names and signatures may change in later releases.
What submit() does
Submitting a form involves a few repeated steps: mark every field as touched so errors appear, check validity, call the server, and report any failure. The submit() function from @angular/forms/signals handles those steps for you.
When you call submit(form, action), Signal Forms does the following:
- Marks all fields in the form as touched.
- Checks whether the form is valid.
- Runs
actiononly if the form is valid. - Treats the value returned by the action as a possible error and reports it on the form.
Step 1 matters most. A user who clicks the button without touching a field has not triggered any "touched" state, so errors that are gated on touched() would stay hidden. submit() touches everything, so those errors appear.
A complete submit handler
The component below builds a profile form and saves it with fetch. It uses the submitting() signal on the form state to disable the button while a request is in flight.
import { Component, signal } from '@angular/core';
import { form, Field, required, submit } from '@angular/forms/signals';
@Component({
selector: 'app-profile',
imports: [Field],
template: `
<form (submit)="onSubmit($event)">
<label>Name <input [field]="profileForm.name" /></label>
@if (profileForm.name().touched() && profileForm.name().invalid()) {
@for (error of profileForm.name().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
}
<button type="submit" [disabled]="profileForm().submitting()">Save</button>
@for (error of profileForm().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
</form>
`,
})
export class ProfileComponent {
private readonly model = signal({ name: '' });
protected readonly profileForm = form(this.model, (path) => {
required(path.name, { message: 'Name is required' });
});
protected async onSubmit(event: Event) {
event.preventDefault();
await submit(this.profileForm, async (f) => {
const response = await fetch('/api/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(f().value()),
});
if (!response.ok) {
return { kind: 'server', message: 'Saving failed. Try again.' };
}
return undefined;
});
}
}Several details in this example are worth noting.
event.preventDefault()stops the browser from doing a full-page form post. You still need it, becausesubmit()does not touch the DOM event.- The action receives the form.
fis the same form you passed in.f().value()reads the current model value as a plain object, which is what you serialize. submit()returns a promise. Await it if you want to run code after the whole cycle finishes, such as navigating away. Check the form state before navigating, because a failed submit also resolves.return undefinedsignals success. Returning an error object signals failure.
Do not disable the button on invalid
The login example earlier in this tutorial used [disabled]="loginForm().invalid()". That is fine for a small form, but it has a cost. A disabled button cannot be clicked, so submit() never runs, and the user never sees which fields are wrong. The form just looks broken.
A better default for longer forms is to leave the button enabled while the user is filling in the form, and disable it only while a request is running:
<button type="submit" [disabled]="profileForm().submitting()">Save</button>Clicking the button then runs submit(), which touches every field and reveals every error at once.
Reporting server errors
The action can return an error object. Signal Forms attaches it to the form, so it appears in profileForm().errors() and makes the form invalid. The object has the same shape as the errors produced by validators: a kind string that identifies the error type, and an optional message for the user.
Use a distinct kind for each failure you want to handle differently:
if (response.status === 409) {
return { kind: 'conflict', message: 'A profile with that name already exists.' };
}
if (!response.ok) {
return { kind: 'server', message: 'Saving failed. Try again.' };
}
return undefined;In the template you can then show a specific message, or branch on error.kind to style it differently.
Errors for a single field
A server often knows which field is wrong, for example "this email is taken". In that case you want the error next to the input, not at the bottom of the form. Signal Forms lets an error returned from the action point at a specific field, using a field property that references that field in the form. The exact shape of this property is part of the experimental API, so check the reference for your Angular version before relying on it.
return {
kind: 'taken',
message: 'That name is already in use.',
field: f.name,
};If the error is attached to the field, it shows up in profileForm.name().errors(). The error display code from the previous chapter then renders it with no changes.
Edge cases and common mistakes
- Network failures throw.
fetchrejects on a network error, and an unhandled throw inside the action is not converted into a form error. Wrap the request intry/catchand return an error object in thecatchblock so the user sees a message. - Server errors are not cleared by editing. An error returned from submit stays on the form until the next submit. Some applications reset it by submitting again; others show it only until the user changes a value. Decide which behavior you want and test it, because it may differ across versions of the experimental API.
submit()does not reset the form. After a successful save, the model still holds the submitted values. To clear the form, set the model signal yourself, for examplethis.model.set({ name: '' }). Writing to the model updates every bound field.- Read from the model, not from the DOM. The model signal is the source of truth. Send
f().value()orthis.model(), and never read values frominputelements. - A valid form can still fail. Client validation catches format problems. Only the server knows about duplicates, permissions, and rate limits, so always handle a non-OK response.
- Async validators delay the action. If a field has a pending asynchronous validator, the form is not yet known to be valid. Treat
pendingas "not ready" in the UI and do not assume the submit runs instantly.
Summary table
| Task | Tool |
|---|---|
| Show all errors after a click | `submit()` touches every field |
| Run code only for valid data | The action passed to `submit()` |
| Report a server failure | Return an error object with `kind` and `message` |
| Prevent double submits | `[disabled]="form().submitting()"` |
| Read the data to send | `f().value()` or the model signal |
| Clear the form after success | `model.set(...)` |
Exercise
A user opens a signup form and clicks "Sign up" without typing anything. The email field uses required(), and its error message is only shown when email().touched() && email().invalid(). The button is not disabled for invalid forms. What happens when submit() runs, and why would adding [disabled]="form().invalid()" to the button change the result?
Show answer
submit() marks every field as touched, so the required-field error becomes visible. The form is invalid, so the action is skipped and no request is sent. If the button were disabled while the form is invalid, the click would never reach submit(). No field would be touched, no error would show, and the user would see a dead button with no explanation.
Exercise
Your action calls fetch('/api/save'). The user is offline, so fetch rejects. What should you add to the action so the user sees a message, and what should the action return?
Show answer
Wrap the fetch call in try/catch. In the catch block, return an error object such as { kind: 'network', message: 'You appear to be offline. Try again.' }. The form then reports it through errors(), and the template can display it like any other error.