Form-Validation
Template-driven forms are perfect for simple forms, and Angular makes it easy to add built-in validation directly in the template.
You can check fields for required input, minimum length, email format, and show real-time validation messages.
Example: Build a form with validation
Step 1: Create a new Angular project
Step 2: Generate a form component
Step 3: Build the form with validation in HTML
In form-component.component.html
You can check fields for required input, minimum length, email format, and show real-time validation messages.
Example: Build a form with validation
Step 1: Create a new Angular project
ng new angular-forms
Step 2: Generate a form component
ng g c form-component
Step 3: Build the form with validation in HTML
In form-component.component.html
<div> <h1>Template-Driven Form Validation</h1> <form #myForm="ngForm" (ngSubmit)="submit()">
<div class="form-group"> <label for="name">Name:</label> <input type="text" id="name" name="name" [(ngModel)]="user.name" #name="ngModel" required minlength="3"> <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger"> <div *ngIf="name.errors?.required">Name is required.</div> <div *ngIf="name.errors?.minlength">Name must be at least 3 characters long.</div> </div> </div> <pre></pre>
<div class="form-group"> <label for="email">Email:</label> <input type="email" id="email" name="email" [(ngModel)]="user.email" #email="ngModel" required email> <div *ngIf="email.invalid && (email.dirty || email.touched)" class="alert alert-danger"> <div *ngIf="email.errors?.required">Email is required.</div> <div *ngIf="email.errors?.email">Invalid email format.</div> </div> </div> <pre></pre>
<button type="submit" [disabled]="myForm.invalid">Submit</button> </form></div>
Step 4: Add the form logic in TypeScript
In form-component.component.ts
import { Component } from '@angular/core';
@Component({ selector: 'app-form-component', templateUrl: './form-component.component.html', styleUrls: ['./form-component.component.css']})export class FormComponentComponent { user = { name: '', email: '' }
submit() { console.log('Form Submitted', this.user); }}
Step 5: Add CSS for better styling
In form-component.component.css
div { text-align: center;}
label { text-align: left;}
.alert { color: red; font-size: 0.9em;}
Step 6: Display the form in the main app
In app.component.html
<app-form-component></app-form-component>
And do not forget to import FormsModule in app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({ imports: [ BrowserModule, FormsModule ], // other code...})export class AppModule { }
Step 7: Run the application
ng serve
Visit http://localhost:4200 and try submitting the form.
Key Point
- Template-driven forms use ngModel and template references for validation.
- Built-in validators like required, minlength, and email make validation easy.
- Angular shows real-time error messages based on form state.