Template Driven Forms
What are template driven forms?
Usually use ngModel
Validation rules imbedded in HTML
Can require end to end testing
Works well for small projects/forms with simple validation
Import Forms Module
Template driven forms requires the FormsModule
for directives like ngModel
. Since this is usually used across multiple forms, it's usually imported in the app.module.
Creating a template driven form
If you don't have a LoginComponent
create one using ng g c login
The form tag has a template variable declared using #loginForm
which points to the ngForm
directive. The submit button is of type submit and the form will call the submit function and pass the form to it.
Template Driven Component
Enter a username, password, and click the submit button. The console should log a similar message: form submitted:{"username":"jesse.sanders@briebug.com","password":"mySecretPassword"}
Setting Required Fields - HTML5 Validation
By adding the required attribute to each input, we can activate the HTML5 validation
Warning: since Angular version 4, you must add ngNativeValidate
for HTML 5 validation to fire.
Why Angular validation?
Control when validation messages appear
Customize validation messages
Complex/programatic validation
Custom validators
Angular Built-In Validators
required
minLength
maxLength
pattern
Adding Validation messages
ngModel
keeps track of each controls validity. Has properties including valid, invalid, touched, untouched, pristine, dirty
Controlling When Validation Messages Appear
By default, validation messages appear immediately We can control when the messages appear by using the ngModelOptions
or ngFormOptions
directive. Usage: <input [ngModelOptions]="{ updateOn: 'blur' }" ... />
or <form [ngFormOptions]="{ updateOn: 'submit' }" ... >
blur - validate when the control loses focus
submit - validate when the form is submitted
change (default) - validate after every keystroke
Use custom variable
Display Form Validation State
Display Field Validation State
Adding Validation Classes
Validation indicators can be great visual cues to users
Other Control Examples
Summary
What are template driven forms?
Import FormsModule
Creating a template driven form/component
HTML5 Validation
Why Angular Validators
Angular Built-In Validators
Adding Validation Messages and when they show
Displaying Form and Field Validation Statuses
Validation Classes
Validating Other Controls
Last updated