Skip to content

Commit 60291fc

Browse files
committed
refactor: form component
1 parent c486c77 commit 60291fc

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

apps/angular/dialog-alert-form/src/app/ui/form.component.ts

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
1-
import { ChangeDetectionStrategy, Component } from '@angular/core';
1+
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
2+
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
23

34
@Component({
45
selector: 'app-form',
56
standalone: true,
7+
imports: [ReactiveFormsModule],
68
template: `
7-
<form class="space-y-4">
9+
<form [formGroup]="form" (ngSubmit)="onSubmit()" class="space-y-4">
810
<div>
911
<label class="sr-only" for="name">Name</label>
1012
<input
1113
class="w-full rounded-lg border-gray-200 p-3 text-sm"
1214
placeholder="Name"
1315
type="text"
14-
name="name"
16+
formControlName="name"
1517
id="name" />
1618
</div>
1719
@@ -22,7 +24,7 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
2224
class="w-full rounded-lg border-gray-200 p-3 text-sm"
2325
placeholder="Email address"
2426
type="email"
25-
name="email"
27+
formControlName="email"
2628
id="email" />
2729
</div>
2830
@@ -32,7 +34,7 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
3234
class="w-full rounded-lg border-gray-200 p-3 text-sm"
3335
placeholder="Phone Number"
3436
type="tel"
35-
name="phone"
37+
formControlName="phone"
3638
id="phone" />
3739
</div>
3840
</div>
@@ -44,19 +46,33 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
4446
class="w-full rounded-lg border-gray-200 p-3 text-sm"
4547
placeholder="Message"
4648
rows="8"
47-
name="message"
49+
formControlName="message"
4850
id="message"></textarea>
4951
</div>
5052
5153
<div class="mt-4">
5254
<button
55+
[disabled]="form.invalid"
5356
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">
5558
Submit
5659
</button>
5760
</div>
5861
</form>
5962
`,
6063
changeDetection: ChangeDetectionStrategy.OnPush,
6164
})
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

Comments
 (0)