This form collects an email and a message. It checks if the email is valid and shows an error if not. The send button is disabled until the email is correct. When sent, it shows a thank you alert and clears the form.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-contact-form',
template: `
<form [formGroup]="contactForm" (ngSubmit)="submitForm()">
<label for="email">Email:</label>
<input id="email" formControlName="email" placeholder="Enter your email" aria-label="Email">
<div *ngIf="email.invalid && email.touched" style="color: red;">
Please enter a valid email.
</div>
<label for="message">Message:</label>
<textarea id="message" formControlName="message" placeholder="Your message" aria-label="Message"></textarea>
<button type="submit" [disabled]="contactForm.invalid">Send</button>
</form>
`
})
export class ContactFormComponent {
contactForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
message: new FormControl('')
});
get email() {
return this.contactForm.get('email')!;
}
submitForm() {
if (this.contactForm.valid) {
console.log('Form data:', this.contactForm.value);
alert('Thank you for your message!');
this.contactForm.reset();
}
}
}