Form Server Actions
Analog supports server-side handling of form submissions and validation.
Setting up the Form
To handle form submissions, use the FormAction directive from the @analogjs/router package. The directives handles collecting the FormData and sending a POST request to the server.
The directive emits after processing the form:
onSuccess: when the form is processing on the server and returns a success response.onError: when the form returns an error response.onStateChange: when the form is submitted.
The example page below submits an email for a newsletter signup.
// src/app/pages/newsletter.page.ts
import { Component, signal } from '@angular/core';
import { FormAction } from '@analogjs/router';
type FormErrors =
| {
email?: string;
}
| undefined;
@Component({
selector: 'app-newsletter-page',
standalone: true,
imports: [FormAction],
template: `
<h3>Newsletter Signup</h3>
@if (!signedUp()) {
<form
method="post"
(onSuccess)="onSuccess()"
(onError)="onError($any($event))"
(onStateChange)="errors.set(undefined)"
>
<div>
<label for="email"> Email </label>
<input type="email" name="email" />
</div>
<button class="button" type="submit">Submit</button>
</form>
@if (errors()?.email) {
<p>{{ errors()?.email }}</p>
}
} @else {
<div>Thanks for signing up!</div>
}
`,
})
export default class NewsletterComponent {
signedUp = signal(false);
errors = signal<FormErrors>(undefined);
onSuccess() {
this.signedUp.set(true);
}
onError(result?: FormErrors) {
this.errors.set(result);
}
}
The FormAction directive submits the form data to the server, which is processed by its handler.