70 lines
1.1 KiB
Markdown
70 lines
1.1 KiB
Markdown
# Angular Forms
|
|
|
|
## Overview
|
|
Angular Forms are used to capture user input and validate data in web applications.
|
|
|
|
Angular provides two types of forms:
|
|
- Template-driven forms
|
|
- Reactive forms
|
|
|
|
---
|
|
|
|
## Template-Driven Forms
|
|
|
|
Template-driven forms rely mainly on HTML templates and Angular directives.
|
|
|
|
Example:
|
|
|
|
<form #userForm="ngForm">
|
|
<input name="username" ngModel required>
|
|
<button type="submit">Submit</button>
|
|
</form>
|
|
|
|
Features:
|
|
- Easy to use
|
|
- Suitable for simple forms
|
|
- Uses `ngModel` directive
|
|
|
|
---
|
|
|
|
## Reactive Forms
|
|
|
|
Reactive forms are defined in TypeScript using FormControl and FormGroup.
|
|
|
|
Example:
|
|
|
|
import { FormGroup, FormControl } from '@angular/forms';
|
|
|
|
profileForm = new FormGroup({
|
|
name: new FormControl(''),
|
|
email: new FormControl('')
|
|
});
|
|
|
|
HTML:
|
|
|
|
<form [formGroup]="profileForm">
|
|
<input formControlName="name">
|
|
<input formControlName="email">
|
|
</form>
|
|
|
|
Features:
|
|
- More control
|
|
- Better for complex forms
|
|
- Easy validation and testing
|
|
|
|
---
|
|
|
|
## Form Validation
|
|
|
|
Angular provides built-in validation such as:
|
|
|
|
- required
|
|
- minlength
|
|
- maxlength
|
|
- pattern
|
|
|
|
Example:
|
|
|
|
<input formControlName="email" required>
|
|
|
|
--- |