43. TDF: Using NgModel and Form Controls
ngModel is the key to creating form controls in TDF. When used inside a <form> tag, it automatically hooks up the input to Angular's form machinery.
The Importance of the name Attribute
In TDF, every input using ngModel must have a unique name attribute. This is how Angular registers the input control within the parent NgForm group.
html
<input type="text" name="firstName" [(ngModel)]="user.firstName">
Form Control States (#control="ngModel")
By assigning a template reference variable to ngModel (e.g., #emailCtrl="ngModel"), we can access the state of the individual control in the template. These states are crucial for validation feedback:
| State Property | Description |
|---|---|
valid | True if the input value passes all validation rules. |
invalid | True if the input value fails any validation rule. |
pristine | True if the user has not changed the value yet. |
dirty | True if the user has changed the value. |
untouched | True if the user has not blurred the input. |
touched | True if the user has blurred the input. |
Displaying Control State Feedback
html <input type="email" name="email" [(ngModel)]="user.email" required email #emailCtrl="ngModel">
Email is required.
Must be a valid email format.
<input [ngClass]="{ 'is-invalid': emailCtrl.invalid && emailCtrl.touched }" ... >