mirror of
https://github.com/Raghu-Ch/angular-challenges.git
synced 2026-02-10 04:43:03 -05:00
refactor: form component
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user