refactor: form component

This commit is contained in:
Timothy Alcaide
2024-04-10 14:24:30 +02:00
committed by thomas
parent c5dd953193
commit 25004e7678

View File

@@ -1,17 +1,19 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form class="space-y-4">
<form [formGroup]="form" (ngSubmit)="onSubmit()" class="space-y-4">
<div>
<label class="sr-only" for="name">Name</label>
<input
class="w-full rounded-lg border-gray-200 p-3 text-sm"
placeholder="Name"
type="text"
name="name"
formControlName="name"
id="name" />
</div>
@@ -22,7 +24,7 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
class="w-full rounded-lg border-gray-200 p-3 text-sm"
placeholder="Email address"
type="email"
name="email"
formControlName="email"
id="email" />
</div>
@@ -32,7 +34,7 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
class="w-full rounded-lg border-gray-200 p-3 text-sm"
placeholder="Phone Number"
type="tel"
name="phone"
formControlName="phone"
id="phone" />
</div>
</div>
@@ -44,14 +46,15 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
class="w-full rounded-lg border-gray-200 p-3 text-sm"
placeholder="Message"
rows="8"
name="message"
formControlName="message"
id="message"></textarea>
</div>
<div class="mt-4">
<button
[disabled]="form.invalid"
type="submit"
class="inline-block w-full rounded-lg border bg-gray-50 px-5 py-3 font-medium text-gray-900 sm:w-auto">
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">
Submit
</button>
</div>
@@ -59,4 +62,17 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FormComponent {}
export class FormComponent {
private fb = inject(FormBuilder);
form = this.fb.nonNullable.group({
name: ['', { validators: [Validators.required] }],
email: ['', [Validators.required, Validators.email]], // other syntax
phone: '',
message: '',
});
onSubmit() {
if (this.form.valid) this.form.reset();
}
}