1
- import { ChangeDetectionStrategy , Component } from '@angular/core' ;
1
+ import { ChangeDetectionStrategy , Component , inject } from '@angular/core' ;
2
+ import { FormBuilder , ReactiveFormsModule , Validators } from '@angular/forms' ;
2
3
3
4
@Component ( {
4
5
selector : 'app-form' ,
5
6
standalone : true ,
7
+ imports : [ ReactiveFormsModule ] ,
6
8
template : `
7
- <form class="space-y-4">
9
+ <form [formGroup]="form" (ngSubmit)="onSubmit()" class="space-y-4">
8
10
<div>
9
11
<label class="sr-only" for="name">Name</label>
10
12
<input
11
13
class="w-full rounded-lg border-gray-200 p-3 text-sm"
12
14
placeholder="Name"
13
15
type="text"
14
- name ="name"
16
+ formControlName ="name"
15
17
id="name" />
16
18
</div>
17
19
@@ -22,7 +24,7 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
22
24
class="w-full rounded-lg border-gray-200 p-3 text-sm"
23
25
placeholder="Email address"
24
26
type="email"
25
- name ="email"
27
+ formControlName ="email"
26
28
id="email" />
27
29
</div>
28
30
@@ -32,7 +34,7 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
32
34
class="w-full rounded-lg border-gray-200 p-3 text-sm"
33
35
placeholder="Phone Number"
34
36
type="tel"
35
- name ="phone"
37
+ formControlName ="phone"
36
38
id="phone" />
37
39
</div>
38
40
</div>
@@ -44,19 +46,33 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
44
46
class="w-full rounded-lg border-gray-200 p-3 text-sm"
45
47
placeholder="Message"
46
48
rows="8"
47
- name ="message"
49
+ formControlName ="message"
48
50
id="message"></textarea>
49
51
</div>
50
52
51
53
<div class="mt-4">
52
54
<button
55
+ [disabled]="form.invalid"
53
56
type="submit"
54
- class="inline-block w-full rounded-lg border bg-gray-50 px-5 py-3 font-medium text-gray-900 sm:w-auto">
57
+ class="inline-block w-full rounded-lg border bg-gray-50 px-5 py-3 font-medium text-gray-900 disabled:cursor-not-allowed disabled:bg-gray-300 sm:w-auto">
55
58
Submit
56
59
</button>
57
60
</div>
58
61
</form>
59
62
` ,
60
63
changeDetection : ChangeDetectionStrategy . OnPush ,
61
64
} )
62
- export class FormComponent { }
65
+ export class FormComponent {
66
+ private fb = inject ( FormBuilder ) ;
67
+
68
+ form = this . fb . nonNullable . group ( {
69
+ name : [ '' , { validators : [ Validators . required ] } ] ,
70
+ email : [ '' , [ Validators . required , Validators . email ] ] , // other syntax
71
+ phone : '' ,
72
+ message : '' ,
73
+ } ) ;
74
+
75
+ onSubmit ( ) {
76
+ if ( this . form . valid ) this . form . reset ( ) ;
77
+ }
78
+ }
0 commit comments