diff --git a/apps/forms/61-simplest-signal-form/src/app/app.component.ts b/apps/forms/61-simplest-signal-form/src/app/app.component.ts
index 48edfb268..d8c36ec9d 100644
--- a/apps/forms/61-simplest-signal-form/src/app/app.component.ts
+++ b/apps/forms/61-simplest-signal-form/src/app/app.component.ts
@@ -1,21 +1,38 @@
import { JsonPipe } from '@angular/common';
import { Component, signal, WritableSignal } from '@angular/core';
+
import {
- FormControl,
- FormGroup,
- ReactiveFormsModule,
- Validators,
-} from '@angular/forms';
+ form,
+ FormField,
+ FormRoot,
+ max,
+ min,
+ required,
+} from '@angular/forms/signals';
+
+type FormData = {
+ name: string;
+ lastname: string;
+ age: number;
+ note: string;
+};
+
+const initialFormData: FormData = {
+ name: '',
+ lastname: '',
+ age: NaN,
+ note: '',
+};
@Component({
selector: 'app-root',
- imports: [ReactiveFormsModule, JsonPipe],
+ imports: [FormField, FormRoot, JsonPipe],
template: `
@@ -60,23 +79,16 @@ import {
- @if (form.controls.age.invalid && !form.controls.age.untouched) {
-
- @if (form.controls.age.hasError('min')) {
- Age must be at least 1
- }
- @if (form.controls.age.hasError('max')) {
- Age must be at most 99
- }
-
+ @if (form.age().invalid() && form.age().touched()) {
+ @for (error of form.age().errors(); track error) {
+
{{ error.message }}
+ }
}
@@ -89,15 +101,15 @@ import {
+ class="w-full rounded-md border border-gray-300 px-4 py-2 transition outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-500" />
@@ -126,35 +138,28 @@ import {
`,
})
export class AppComponent {
- form = new FormGroup({
- name: new FormControl('', {
- validators: Validators.required,
- nonNullable: true,
- }),
- lastname: new FormControl('', { nonNullable: true }),
- age: new FormControl(null, [
- Validators.min(1),
- Validators.max(99),
- ]),
- note: new FormControl('', { nonNullable: true }),
- });
+ model = signal(initialFormData);
- submittedData: WritableSignal<{
- name: string;
- lastname: string;
- age: number | null;
- note: string;
- } | null> = signal(null);
+ form = form(
+ this.model,
+ (schemaPath) => {
+ required(schemaPath.name, { message: 'Name is required' });
+ min(schemaPath.age, 1, { message: 'Age must be at least 1' });
+ max(schemaPath.age, 99, { message: 'Age must be at most 99' });
+ },
+ {
+ submission: {
+ action: async (f) => {
+ this.submittedData.set(f().value());
+ },
+ },
+ },
+ );
- onSubmit(): void {
- if (this.form.valid) {
- this.submittedData.set(this.form.getRawValue());
- console.log('Form submitted:', this.submittedData);
- }
- }
+ submittedData: WritableSignal = signal(null);
onReset(): void {
- this.form.reset();
+ this.form().reset(initialFormData);
this.submittedData.set(null);
}
}