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

Simple Form

-
+
@@ -46,7 +52,7 @@ import {
@@ -60,21 +66,16 @@ import { - @if (form.controls.age.invalid && !form.controls.age.untouched) { + @if (form.age().invalid() && form.age().touched()) {

- @if (form.controls.age.hasError('min')) { - Age must be at least 1 - } - @if (form.controls.age.hasError('max')) { - Age must be at most 99 + @for (error of form.age().errors(); track error) { + {{ error.message }} }

} @@ -89,7 +90,7 @@ import {
@@ -97,7 +98,7 @@ import {
@@ -126,35 +127,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 }), + // we cannot use null for initial value of number field because null is not supported by native input[type="number"] + // https://github.com/angular/angular/issues/65454 + formModel = signal({ + name: '', + lastname: '', + age: NaN, + note: '', + }); + + form = form(this.formModel, (path) => { + required(path.name, { message: 'Name is required' }); + min(path.age, 1, { message: 'Age must be at least 1' }); + max(path.age, 99, { message: 'Age must be at most 99' }); }); - submittedData: WritableSignal<{ - name: string; - lastname: string; - age: number | null; - note: string; - } | null> = signal(null); + submittedData = signal(null); onSubmit(): void { - if (this.form.valid) { - this.submittedData.set(this.form.getRawValue()); - console.log('Form submitted:', this.submittedData); + if (this.form().valid()) { + this.submittedData.set(this.formModel()); + console.log('Form submitted:', this.submittedData()); } } onReset(): void { - this.form.reset(); + this.formModel.set({ + name: '', + lastname: '', + age: NaN, + note: '', + }); this.submittedData.set(null); } }