Angular Forms
Angular Forms provides a robust mechanism for handling user input and managing form data in web applications. They offer flexibility through two main approaches: Template Driven Forms and Model Driven (Reactive) Forms.Example
// In your HTML template
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
<input type="text" name="username" ngModel required>
<input type="email" name="email" ngModel required email>
<button type="submit">Submit</button>
</form>
FormControl
FormControl is a fundamental building block in Angular Forms that represents an individual form control element. It encapsulates the state and validation of the control.Example
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
<input [formControl]="username" placeholder="Username">
`,
})
export class MyFormComponent {
username = new FormControl('');
}
FormGroup
FormGroup is used to group related form controls together, making it easier to manage and validate them collectively.Example
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
<form [formGroup]="userForm">
<input formControlName="username" placeholder="Username">
<input formControlName="email" placeholder="Email">
</form>
`,
})
export class MyFormComponent {
userForm = new FormGroup({
username: new FormControl(''),
email: new FormControl(''),
});
}
FormArray
FormArray is a specialized form control that manages an array of form controls, which is useful for dynamic forms with repeating elements.Example
import { Component } from '@angular/core';
import { FormBuilder, FormArray } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
<form [formGroup]="userForm">
<div formArrayName="hobbies">
<div *ngFor="let hobby of hobbies.controls; let i = index">
<input [formControlName]="i" placeholder="Hobby {{ i + 1 }}">
</div>
</div>
</form>
`,
})
export class MyFormComponent {
userForm = this.formBuilder.group({
hobbies: this.formBuilder.array(['Reading', 'Gaming']),
});
get hobbies() {
return this.userForm.get('hobbies') as FormArray;
}
}
FormGroupDirective
FormGroupDirective is a directive in Angular that connects an existing FormGroup to a form element in the template. It's particularly useful when you want to manage form controls explicitly and interact with the form as a whole.Example
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
<form [formGroup]="userForm">
<input formControlName="username" placeholder="Username">
<input formControlName="email" placeholder="Email">
</form>
`,
})
export class MyFormComponent {
userForm = new FormGroup({
username: new FormControl(''),
email: new FormControl(''),
});
}
ngModel
ngModel is a two-way data binding directive used in Template Driven Forms. It allows you to bind form controls to component properties, automatically keeping them in sync.Example
<input [(ngModel)]="username" name="username" required>
FormBuilder
FormBuilder is a utility class that simplifies the creation of FormGroup instances and their controls, making form setup cleaner and more concise.Example
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
<form [formGroup]="userForm">
<input formControlName="username" placeholder="Username">
<input formControlName="email" placeholder="Email">
</form>
`,
})
export class MyFormComponent {
userForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.userForm = this.formBuilder.group({
username: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
}
}
Template Driven Form Validation
Template Driven Forms in Angular allow you to perform validation directly in the template using built-in directives like ngModel and HTML5 attributes.Example
<input [(ngModel)]="username" name="username" required minlength="3">
Reactive Form Validation
Reactive Forms offers more extensive and programmatic validation capabilities by defining validation rules in TypeScript code.Example
const userForm = new FormGroup({
username: new FormControl('', [Validators.required, Validators.minLength(3)]),
email: new FormControl('', [Validators.required, Validators.email]),
});
Custom Validations
Angular allows you to create custom validation functions to meet specific validation requirements for your application.Example
function customValidator(control: AbstractControl): ValidationErrors | null {
if (control.value && control.value.includes('example')) {
return { forbiddenValue: 'Value contains "example"' };
}
return null;
}
const userForm = new FormGroup({
username: new FormControl('', [Validators.required, customValidator]),
});