- @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);
}
}