Back to course

TDF: Using NgModel and form controls

The Complete Angular Developer: From Zero to Hero

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 PropertyDescription
validTrue if the input value passes all validation rules.
invalidTrue if the input value fails any validation rule.
pristineTrue if the user has not changed the value yet.
dirtyTrue if the user has changed the value.
untouchedTrue if the user has not blurred the input.
touchedTrue 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 }" ... >