Creating forms in Angular involves using Angular’s powerful form handling capabilities. Angular provides two approaches to handle forms: Template-driven forms and Reactive forms. Reactive forms provide a more robust and scalable way to handle complex form requirements.
Here’s a step-by-step guide to creating forms using Angular Reactive Forms.
Create a new Angular project:
ng new my-form-app
cd my-form-app
Install Angular Material (optional, for UI components):
ng add @angular/material
Generate a new component:
ng generate component my-form
Add ReactiveFormsModule to your AppModule:
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MyFormComponent } from './my-form/my-form.component';
@NgModule({
declarations: [
AppComponent,
MyFormComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Import necessary modules in your form component:
// src/app/my-form/my-form.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
age: [null, [Validators.required, Validators.min(1)]]
});
}
onSubmit() {
if (this.myForm.valid) {
console.log(this.myForm.value);
}
}
}
Create the template for the form:
<!-- src/app/my-form/my-form.component.html -->
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div>
<label for="name">Name</label>
<input id="name" formControlName="name">
<div *ngIf="myForm.get('name')?.invalid && myForm.get('name')?.touched">
Name is required
</div>
</div>
<div>
<label for="email">Email</label>
<input id="email" formControlName="email">
<div *ngIf="myForm.get('email')?.invalid && myForm.get('email')?.touched">
<span *ngIf="myForm.get('email')?.errors?.['required']">Email is required</span>
<span *ngIf="myForm.get('email')?.errors?.['email']">Invalid email address</span>
</div>
</div>
<div>
<label for="age">Age</label>
<input id="age" type="number" formControlName="age">
<div *ngIf="myForm.get('age')?.invalid && myForm.get('age')?.touched">
<span *ngIf="myForm.get('age')?.errors?.['required']">Age is required</span>
<span *ngIf="myForm.get('age')?.errors?.['min']">Age must be greater than zero</span>
</div>
</div>
<button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
Add some basic styles:
/* src/app/my-form/my-form.component.css */
form {
max-width: 400px;
margin: 0 auto;
}
div {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
div div {
color: red;
font-size: 0.8em;
}
button {
padding: 10px 15px;
background-color: #007bff;
border: none;
color: white;
cursor: pointer;
}
button:disabled {
background-color: #cccccc;
}
Run the following command to start the development server:
ng serve
Open your browser and navigate to http://localhost:4200/
. You should see your form with the name, email, and age fields, along with validation.
Validators.required
and Validators.email
for common validation tasks.By following these steps, you’ve created a robust form using Angular’s reactive forms, ensuring efficient form handling and validation.