Template-Driven Forms
Template-driven forms are the simplest way to build forms in Angular. They work similar to how you might handle forms in plain HTML, with Angular adding some superpowers.
In this approach, you define the form structure in the template using Angular directives like
ngModel, ngForm, and ngModelGroup. The component class mainly holds the data model and submission logic.Basic Example: Login Form
Component class:
import { Component } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent {
user = {
email: '',
password: ''
};
onSubmit(form: any) {
console.log('Form submitted:', this.user);
console.log('Form valid?', form.valid);
}
}
Template (login.component.html):
<form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
<div>
<label>Email:</label>
<input type="email" name="email" [(ngModel)]="user.email" required email #email="ngModel">
<div *ngIf="email.invalid && email.touched">
<small *ngIf="email.errors?.required">Email is required.</small>
<small *ngIf="email.errors?.email">Enter a valid email.</small>
</div>
</div>
<div>
<label>Password:</label>
<input type="password" name="password" [(ngModel)]="user.password" required minlength="6" #password="ngModel">
<div *ngIf="password.invalid && password.touched">
<small *ngIf="password.errors?.required">Password is required.</small>
<small *ngIf="password.errors?.minlength">Password must be at least 6 characters.</small>
</div>
</div>
<button type="submit" [disabled]="loginForm.invalid">Login</button>
</form>
Key Directives:
#loginForm="ngForm"– creates a reference to the form, tracks overall validity.ngSubmit– handles form submission.[(ngModel)]– two-way binding between input and component property.nameattribute – required for ngModel to work.#email="ngModel"– creates a reference to the control, gives access to validation state.required,email,minlength– built-in validators.loginForm.invalid– disables submit button when form is invalid.
Two Minute Drill
- Template-driven forms are defined mostly in the HTML.
- Use ngForm, ngModel, and ngModelGroup directives.
- Two-way binding with [(ngModel)] syncs data.
- Validation uses HTML5 attributes (required, email, minlength).
- Access validation state via template reference variables.
- Simple and quick for basic forms.
Need more clarification?
Drop us an email at career@quipoinfotech.com
