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..411ec6c17 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,23 @@ import { JsonPipe } from '@angular/common'; import { Component, signal, WritableSignal } from '@angular/core'; -import { - FormControl, - FormGroup, - ReactiveFormsModule, - Validators, -} from '@angular/forms'; +import { Field, form, max, min, required } from '@angular/forms/signals'; + +interface IFormData { + name: string; + lastname: string; + age: number; + note: string; +} @Component({ selector: 'app-root', - imports: [ReactiveFormsModule, JsonPipe], + imports: [Field, JsonPipe], template: `

Simple Form

-
+
@@ -46,7 +50,7 @@ import {
@@ -60,23 +64,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().errors().length > 0 && form.age().touched()) { + @for (error of form.age().errors(); track error) { +

{{ error.message }}

+ } }
@@ -89,7 +86,7 @@ import { @@ -97,7 +94,7 @@ import {
@@ -126,35 +123,37 @@ 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 }), + formDefaults: IFormData = { + name: '', + lastname: '', + age: null!, + note: '', + }; + + formModel = signal(this.formDefaults); + + form = form(this.formModel, (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' }); }); - submittedData: WritableSignal<{ - name: string; - lastname: string; - age: number | null; - note: string; - } | null> = signal(null); + submittedData: WritableSignal = signal(null); - onSubmit(): void { - if (this.form.valid) { - this.submittedData.set(this.form.getRawValue()); + onSubmit(e: Event): void { + e.preventDefault(); + if (this.form().valid()) { + this.submittedData.set({ + ...this.form().value(), + // Form returns age as string from the input for some reason, convert it to number + age: +this.form().value().age, + }); console.log('Form submitted:', this.submittedData); } } onReset(): void { - this.form.reset(); + this.form().reset(this.formDefaults); this.submittedData.set(null); } }