Forms
About
Angular will not automatically detect the inputs and selects.
Angular injects a couple of classes on the inputs and selects.
Best Practices
Mainly use
Reactive
forms.Use
FormBuilder
service to be able to use TypedFormControls
by default.It will thought create
FormControls
withType | null
.
To avoid having
nullable
types, useNonNullableFormBuilder
service.
Details
Foundation Classes
FormControl
FormControl
Tracks the value and validation status of an individual form control (input).
Its parameters are (in order):
The initial value.
Array of Validators.
Array of async Validators.
FormGroup
FormGroup
Defines a form with a fixed set of form controls that you can manage together.
Its parameters are (in order):
Object of multiple
FormControl
,FormGroup
orFormArray
.
FormArray
FormArray
Defines a dynamic form, where you can add and remove controls at run time.
ControlValueAcessor
Creates a bridge between Angular FormControl
instances and built-in DOM elements.
Control States
These are classes added to the element, so you can define custom CSS for them.
The form
itself will also receive these state classes.
ng-touched
: The control has been visited, even clicked (had focus on).ng-untouched
: The control hasn't been visited yet.ng-dirty
: The control's value has been changed.ng-pristine
: The control's value hasn't been changed.ng-valid
: The control's value is valid.ng-invalid
: The control's value isn't valid.
ngForm
ngForm
ngForm
has a submitted value on the <form>
, after you <form #thisForm="ngForm">
, that is useful if you want to display error only after the form has been submit.
Resetting the Form
You can reset the form values
and states
by calling .reset()
method.
You may provide as parameter values to be used.
Otherwise it will the the initial values as default.
But these will only reset the groups and controls validations and values.
To reset the #form
itself from have been submitted
you will have to:
Provide the
<form #thisForm="ngForm">
with a Local Template Reference.Access the reference with a
viewChild()
or access it on the(ngSubmit)="handleSubmit(thisForm)"
function.Call
resetForm()
ofngForm
on the variable, this will reset thesubmitted
of the form to false again.
Last updated