Chapter 7: Angular Forms and Validation
Angular provides two approaches for working with forms: template-driven forms and reactive forms. In this chapter, we will explore both approaches in detail, including form creation, form validation, custom validation, handling form submission, and manipulating form data.
- Working with Template-Driven Forms:
Template-driven forms are easy to use and require less code compared to reactive forms. Here’s how you can work with template-driven forms:
Step 1: Import the FormsModule
in your module file (app.module.ts
):
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule
],
// ...
})
export class AppModule { }
Step 2: Create a form in your component’s template:
<form #myForm="ngForm" (ngSubmit)="submitForm(myForm)">
<input type="text" name="name" ngModel required>
<button type="submit">Submit</button>
</form>
Step 3: Implement the submitForm
method in your component to handle form submission:
import { Component } from '@angular/core';
@Component({
// ...
})
export class MyComponent {
submitForm(form: NgForm): void {
if (form.valid) {
// Form is valid, submit data
} else {
// Form is invalid, display validation errors
}
}
}
- Working with Reactive Forms and Form Validation:
Reactive forms provide more flexibility and control over form handling and validation. Here’s how you can work with reactive forms:
Step 1: Import the ReactiveFormsModule
in your module file (app.module.ts
):
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
ReactiveFormsModule
],
// ...
})
export class AppModule { }
Step 2: Create a form group in your component:
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
// ...
})
export class MyComponent {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.myForm = this.formBuilder.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
age: ['', Validators.min(18)],
});
}
submitForm(): void {
if (this.myForm.valid) {
// Form is valid, submit data
} else {
// Form is invalid, display validation errors
}
}
}
Step 3: Bind form controls to your template:
<form [formGroup]="myForm" (ngSubmit)="submitForm()">
<input type="text" formControlName="name">
<input type="email" formControlName="email">
<input type="number" formControlName="age">
<button type="submit">Submit</button>
</form>
- Custom Form Validation:
Angular allows you to create custom validators to perform complex form validation. Here’s an example of creating a custom validator for password confirmation:
Step 1: Create a custom validator function:
import { FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
export function passwordMatchValidator(): ValidatorFn {
return (formGroup: FormGroup): ValidationErrors | null => {
const password = formGroup.get('password').value;
const confirmPassword = formGroup.get('confirmPassword').value;
return password === confirmPassword ? null : { passwordMismatch: true };
};
}
Step 2: Add the custom validator to your form group:
this.myForm = this.formBuilder.group({
password: ['',
Validators.required],
confirmPassword: ['', Validators.required],
}, { validators: passwordMatchValidator() });
- Handling Form Submission and Manipulating Form Data:
To handle form submission, you can use the (ngSubmit)
event on your form and call a method in your component. Inside the method, you can access the form values and perform further actions:
<form [formGroup]="myForm" (ngSubmit)="submitForm()">
<!-- Form controls here -->
<button type="submit">Submit</button>
</form>
submitForm(): void {
if (this.myForm.valid) {
const formData = this.myForm.value;
// Perform actions with form data
}
}
You can also manipulate form data before submitting it by accessing individual form controls:
submitForm(): void {
if (this.myForm.valid) {
const name = this.myForm.get('name').value;
const email = this.myForm.get('email').value;
// Perform actions with name and email
}
}
By understanding and implementing forms and validation in Angular, you can create interactive and user-friendly input forms in your applications.