-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathapp.component.ts
More file actions
68 lines (63 loc) · 1.49 KB
/
app.component.ts
File metadata and controls
68 lines (63 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { JsonPipe } from '@angular/common';
import {
ChangeDetectionStrategy,
Component,
signal,
WritableSignal,
} from '@angular/core';
import {
form,
FormField,
FormRoot,
max,
min,
required,
} from '@angular/forms/signals';
type UserData = {
name: string;
lastname: string;
age: number | null;
note: string;
};
@Component({
selector: 'app-root',
imports: [JsonPipe, FormField, FormRoot],
templateUrl: './app.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
private readonly _initialData: UserData = {
name: '',
lastname: '',
age: null,
note: '',
};
private _userModel = signal<UserData>(this._initialData);
protected userForm = form(
this._userModel,
(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 () => {
if (this.userForm().valid()) {
this.setSubmittedData();
}
},
},
},
);
protected submittedData: WritableSignal<UserData | null> = signal(null);
public onReset(): void {
this.userForm().reset(this._initialData);
this.setSubmittedData();
}
private setSubmittedData(): void {
const formData = this._userModel();
console.log('Form submitted:', formData);
this.submittedData.set(formData);
}
}