Angular Forms
In Angular, there are two ways to create forms: template-driven forms and reactive forms.
Template-driven forms are simpler and less flexible, and rely on two-way data binding. In this approach, you create a form in the HTML template, and Angular automatically generates the form controls and handles their state. However, template-driven forms are untyped, meaning that you do not get type checking or auto-completion for your form controls.
On the other hand, reactive forms are more powerful and flexible, and provide a more explicit and type-safe way to create and manage forms. With reactive forms, you define the form controls and their properties in the component class, and bind them to the form in the template. Reactive forms are fully typed, meaning that you get full type checking and auto-completion for your form controls.
In summary, while template-driven forms in Angular are untyped and offer less control, reactive forms provide a more explicit and type-safe way to create and manage forms.
Template-driven forms
To create template-driven forms in Angular, you can follow these steps:
- Import the FormsModule in your NgModule. This provides the necessary directives for creating template-driven forms.
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule
]
})
export class YourModule { }
- Create the form in your component template using the ngForm directive, and add form controls using ngModel. For example, to create a simple login form with email and password fields:
<form #loginForm="ngForm">
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" [(ngModel)]="email" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" [(ngModel)]="password" required>
</div>
<button type="submit">Login</button>
</form>
- Bind the form data to your component class properties using two-way data binding with [(ngModel)] syntax. For example, in your component class:
import { Component } from '@angular/core';
@Component({
selector: 'app-login',
template: `
<form #loginForm="ngForm">
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" [(ngModel)]="email" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" [(ngModel)]="password" required>
</div>
<button type="submit">Login</button>
</form>
`
})
export class LoginComponent {
email: string;
password: string;
onSubmit() {
// handle form submission
}
}
- Handle the form submission by binding to the ngSubmit event on the form element and calling a method in your component class. For example:
<form #loginForm="ngForm" (ngSubmit)="onSubmit()">
...
</form>
export class LoginComponent {
...
onSubmit() {
console.log(this.email, this.password);
// handle form submission
}
}
These are the basic steps to create a template-driven form in Angular. There are also many other directives and features you can use, such as ngModelGroup, ngModelChange, and ngFormModel.
Reactive Forms
To create reactive forms in Angular, you can follow these steps:
- Import the ReactiveFormsModule in your NgModule. This provides the necessary classes and directives for creating reactive forms.
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
ReactiveFormsModule
]
})
export class YourModule { }
- Create the form controls and form group in your component class using the FormControl and FormGroup classes. For example, to create a simple login form with email and password fields:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
template: `
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div>
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email">
<div *ngIf="email.invalid && (email.dirty || email.touched)">
<div *ngIf="email.errors.required">Email is required.</div>
<div *ngIf="email.errors.email">Email must be a valid email address.</div>
</div>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" formControlName="password">
<div *ngIf="password.invalid && (password.dirty || password.touched)">
<div *ngIf="password.errors.required">Password is required.</div>
</div>
</div>
<button type="submit" [disabled]="loginForm.invalid">Login</button>
</form>
`
})
export class LoginComponent {
loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', Validators.required)
});
onSubmit() {
console.log(this.loginForm.value);
// handle form submission
}
get email() { return this.loginForm.get('email'); }
get password() { return this.loginForm.get('password'); }
}
- Bind the form group to your component template using the formGroup directive, and add form controls using the formControlName directive. For example:
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div>
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email">
<div *ngIf="email.invalid && (email.dirty || email.touched)">
<div *ngIf="email.errors.required">Email is required.</div>
<div *ngIf="email.errors.email">Email must be a valid email address.</div>
</div>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" formControlName="password">
<div *ngIf="password.invalid && (password.dirty || password.touched)">
<div *ngIf="password.errors.required">Password is required.</div>
</div>
</div>
<button type="submit" [disabled]="loginForm.invalid">Login</button>
</form>
- Handle the form submission by binding to the ngSubmit event on the form element and calling a method in your component class. For example:
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
...
</form>
export class LoginComponent {
...
onSubmit() {
console.log(this.loginForm.value);
// handle
Reactive forms are used for more complex forms, where you need to have more control over the validation and form submission process. Reactive forms allow you to define the form structure and validation rules in the component class, which makes it easier to manage and maintain the form. Reactive forms are also more scalable, as you can create form controls dynamically at runtime, and reuse the same form controls in different parts of your application.
Template-driven forms are used for simpler forms, where you need to quickly create a form with minimal configuration. With template-driven forms, you define the form structure and validation rules directly in the template using directives like ngModel and ngForm. This makes template-driven forms easier to set up and configure, but they can become more difficult to maintain as the form becomes more complex.
In general, you should choose reactive forms when you need more control over the form and validation process, or when you need to create more complex and dynamic forms. You should choose template-driven forms for simpler forms where you need to quickly create a form with minimal configuration. Ultimately, the choice between reactive forms and template-driven forms depends on the specific requirements of your project and the complexity of the form you are trying to create.
Thanks for reading — I hope you found this article useful. Happy coding! :)
source: https://angular.io/docs