Template-Driven Forms
Template-Driven forms build their form control models in the template layout using directive properties, making them simple to write and maintain.
1 ngModel, ngForm and validation checks
Template-driven forms rely on three core features:
- ngModel: Binds individual form inputs to properties on your component class.
- #myForm="ngForm": Creates a local template reference variable mapping to Angular's form control object.
- CSS validation states: Angular automatically applies classes like
ng-valid,ng-invalid,ng-dirty, andng-touched, allowing you to style invalid input fields dynamically.
2 Template-Driven Form Implementation
Let's check how to build a basic form in HTML:
HTML — Template Form
<!-- #myForm exports ngForm instance -->
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<div>
<label>Email Address:</label>
<input type="email" name="email" ngModel required #emailInput="ngModel">
<span *ngIf="emailInput.invalid && emailInput.touched" class="error">
A valid email is required.
</span>
</div>
<button type="submit" [disabled]="myForm.invalid">Submit Form</button>
</form>
3 Code Challenge
Challenge: Add a password input field to the form above. Apply validation rules (minimum length of 6 characters, required field), and display a warning if validation checks fail.