? Template-driven Forms ✔️ Validation ? User Input
Template-driven forms validation in Angular lets you validate user input directly in the HTML template using built-in HTML validators and Angular directives like ngModel and ngForm. Angular keeps track of the form state (valid, invalid, touched, dirty, submitted) so that you can show or hide validation error messages dynamically and control when the user is allowed to submit the form.
ngModel and ngForm.required, minlength, and email enforce basic rules.valid, invalid, touched, dirty, pristine, submitted) drives error display.*ngIf and control errors (e.g., control.errors?.required).form.valid to prevent invalid submissions.ngForm to the form using a template reference:<form #userForm="ngForm"> ... </form>ngModel and a name:<input name="name" [(ngModel)]="user.name" required minlength="3">#nameRef="ngModel" then use nameRef.valid, nameRef.invalid, etc.*ngIf="nameRef.errors?.required", *ngIf="nameRef.errors?.minlength".[disabled]="!userForm.form.valid" on the submit button.
// app.component.ts - template-driven form with validation
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user = { name: '', email: '' };
submitForm(form: any) {
console.log('Form Submitted', this.user);
console.log('Is form valid?', form.valid);
}
}
// app.component.html - template with Angular validation
<form #userForm="ngForm" (ngSubmit)="submitForm(userForm)">
<label for="name">Name:</label>
<input
id="name"
type="text"
name="name"
[(ngModel)]="user.name"
required
minlength="3"
#nameRef="ngModel"
/>
<div *ngIf="nameRef.invalid && (nameRef.dirty || nameRef.touched || userForm.submitted)">
<span *ngIf="nameRef.errors?.required">Name is required.</span>
<span *ngIf="nameRef.errors?.minlength">Name must be at least 3 characters.</span>
</div>
<br /><br />
<label for="email">Email:</label>
<input
id="email"
type="email"
name="email"
[(ngModel)]="user.email"
required
email
#emailRef="ngModel"
/>
<div *ngIf="emailRef.invalid && (emailRef.dirty || emailRef.touched || userForm.submitted)">
<span *ngIf="emailRef.errors?.required">Email is required.</span>
<span *ngIf="emailRef.errors?.email">Invalid email format.</span>
</div>
<br /><br />
<button type="submit" [disabled]="!userForm.form.valid">Submit</button>
</form>
name and email are empty.NgForm instance (userForm) and form controls for name and email.nameRef and emailRef update their state (dirty, touched, valid, etc.).userForm.form.valid becomes true.submitForm() runs and logs the user object and form validity.name attribute on inputs so that ngModel can register them with the form.#nameRef="ngModel" to keep templates clean and readable.required, minlength, type="email") with Angular directives.