Forms & Validation
Angular Template Driven Forms
A template-driven form uses ngModel on each control and lets Angular build the form model implicitly. A template reference variable exposes the form state for validation display and submission.
What is Template Driven Forms in Angular?
A template-driven form uses ngModel on each control and lets Angular build the form model implicitly. A template reference variable exposes the form state for validation display and submission.
Template Driven Forms example
<form #f="ngForm" (ngSubmit)="submit(f)">
<input name="email" [(ngModel)]="model.email" required email #email="ngModel">
@if (email.invalid && email.touched) {
<small>Enter a valid email address</small>
}
<input name="phone" [(ngModel)]="model.phone" required pattern="^[6-9]\d{9}$">
<button [disabled]="f.invalid">Apply</button>
</form>How this works
#f="ngForm" exposes the whole form; #email="ngModel" exposes one control. Both carry valid, invalid, touched, dirty and errors, which is what drives the conditional error message.
Key points to remember
- Import FormsModule, and give every ngModel control a name attribute.
- ngSubmit fires on submit and prevents the default page reload.
- Control state flags: valid, invalid, pristine, dirty, touched, untouched.
Common mistakes with Template Driven Forms
- A missing name attribute, so the control never registers with the form.
- Showing errors before the user has touched the field.
Angular Template Driven Forms— Interview Questions & FAQs
What does #f="ngForm" do?+
It creates a template reference variable bound to the NgForm directive, giving the template access to the form’s validity, values and submission state.
